file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// File: contracts/ErrorReporter.sol pragma solidity 0.4.24; contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. */ event Failure(uint256 error, uint256 info, uint256 detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, ETHER_AMOUNT_MISMATCH_ERROR } /** * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, SEND_ETHER_ADMIN_CHECK_FAILED, ETHER_AMOUNT_MISMATCH_ERROR } /** * @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } // File: contracts/CarefulMath.sol // Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2 // and added custom functions related to Alkemi pragma solidity 0.4.24; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol */ contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } // File: contracts/Exponential.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; contract Exponential is ErrorReporter, CarefulMath { // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; // Though unused, the below variable cannot be deleted as it will hinder upgradeability // Will be cleared during the next compiler version upgrade uint256 constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint256 doubleScaledProductWithHalfScale) = add( halfExpScale, doubleScaledProduct ); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint256 product) = div( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } // File: contracts/InterestRateModel.sol pragma solidity 0.4.24; /** * @title InterestRateModel Interface * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); } // File: contracts/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; // token decimals uint8 public decimals; // maximum is 18 decimals /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/EIP20NonStandardInterface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * !!!!!!!!!!!!!! * !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public; /** * * !!!!!!!!!!!!!! * !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/SafeToken.sol pragma solidity 0.4.24; contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn( address asset, address from, uint256 amount ) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address asset, address from, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } function doApprove( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.approve(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } // File: contracts/AggregatorV3Interface.sol pragma solidity 0.4.24; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts/ChainLink.sol pragma solidity 0.4.24; contract ChainLink { mapping(address => AggregatorV3Interface) internal priceContractMapping; address public admin; bool public paused = false; address public wethAddressVerified; address public wethAddressPublic; AggregatorV3Interface public USDETHPriceFeed; uint256 constant expScale = 10**18; uint8 constant eighteen = 18; /** * Sets the admin * Add assets and set Weth Address using their own functions */ constructor() public { admin = msg.sender; } /** * Modifier to restrict functions only by admins */ modifier onlyAdmin() { require( msg.sender == admin, "Only the Admin can perform this operation" ); _; } /** * Event declarations for all the operations of this contract */ event assetAdded( address indexed assetAddress, address indexed priceFeedContract ); event assetRemoved(address indexed assetAddress); event adminChanged(address indexed oldAdmin, address indexed newAdmin); event verifiedWethAddressSet(address indexed wethAddressVerified); event publicWethAddressSet(address indexed wethAddressPublic); event contractPausedOrUnpaused(bool currentStatus); /** * Allows admin to add a new asset for price tracking */ function addAsset(address assetAddress, address priceFeedContract) public onlyAdmin { require( assetAddress != address(0) && priceFeedContract != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface( priceFeedContract ); emit assetAdded(assetAddress, priceFeedContract); } /** * Allows admin to remove an existing asset from price tracking */ function removeAsset(address assetAddress) public onlyAdmin { require( assetAddress != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface(address(0)); emit assetRemoved(assetAddress); } /** * Allows admin to change the admin of the contract */ function changeAdmin(address newAdmin) public onlyAdmin { require( newAdmin != address(0), "Asset or Price Feed address cannot be 0x00" ); emit adminChanged(admin, newAdmin); admin = newAdmin; } /** * Allows admin to set the weth address for verified protocol */ function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin { require(_wethAddressVerified != address(0), "WETH address cannot be 0x00"); wethAddressVerified = _wethAddressVerified; emit verifiedWethAddressSet(_wethAddressVerified); } /** * Allows admin to set the weth address for public protocol */ function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin { require(_wethAddressPublic != address(0), "WETH address cannot be 0x00"); wethAddressPublic = _wethAddressPublic; emit publicWethAddressSet(_wethAddressPublic); } /** * Allows admin to pause and unpause the contract */ function togglePause() public onlyAdmin { if (paused) { paused = false; emit contractPausedOrUnpaused(false); } else { paused = true; emit contractPausedOrUnpaused(true); } } /** * Returns the latest price scaled to 1e18 scale */ function getAssetPrice(address asset) public view returns (uint256, uint8) { // Return 1 * 10^18 for WETH, otherwise return actual price if (!paused) { if ( asset == wethAddressVerified || asset == wethAddressPublic ){ return (expScale, eighteen); } } // Capture the decimals in the ERC20 token uint8 assetDecimals = EIP20Interface(asset).decimals(); if (!paused && priceContractMapping[asset] != address(0)) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceContractMapping[asset].latestRoundData(); startedAt; // To avoid compiler warnings for unused local variable // If the price data was not refreshed for the past 1 day, prices are considered stale // This threshold is the maximum Chainlink uses to update the price feeds require(timeStamp > (now - 86500 seconds), "Stale data"); // If answeredInRound is less than roundID, prices are considered stale require(answeredInRound >= roundID, "Stale Data"); if (price > 0) { // Magnify the result based on decimals return (uint256(price), assetDecimals); } else { return (0, assetDecimals); } } else { return (0, assetDecimals); } } function() public payable { require( msg.sender.send(msg.value), "Fallback function initiated but refund failed" ); } } // File: contracts/AlkemiWETH.sol // Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3 pragma solidity 0.4.24; contract AlkemiWETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); emit Transfer(address(0), msg.sender, msg.value); } function withdraw(address user, uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; user.transfer(wad); emit Withdrawal(msg.sender, wad); emit Transfer(msg.sender, address(0), wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // File: contracts/RewardControlInterface.sol pragma solidity 0.4.24; contract RewardControlInterface { /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external; /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external; /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external; /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address market, bool isVerified ) external; } // File: contracts/AlkemiEarnVerified.sol pragma solidity 0.4.24; contract AlkemiEarnVerified is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnVerified` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: 125 * (10**16)}); originationFee = Exp({mantissa: (10**15)}); liquidationDiscount = Exp({mantissa: (10**17)}); // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnVerified, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Modifier to check if the caller is the admin of the contract */ modifier onlyOwner() { require(msg.sender == admin, "Owner check failed"); _; } /** * @dev Modifier to check if the caller is KYC verified */ modifier onlyCustomerWithKYC() { require( customersWithKYC[msg.sender], "KYC_CUSTOMER_VERIFICATION_CHECK_FAILED" ); _; } /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev Mapping to identify the list of KYC Admins */ mapping(address => bool) public KYCAdmins; /** * @dev Mapping to identify the list of customers with verified KYC */ mapping(address => bool) public customersWithKYC; /** * @dev Mapping to identify the list of customers with Liquidator roles */ mapping(address => bool) public liquidators; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; Exp supplyTotalValue; Exp sumSupplies; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev Events to notify the frontend of all the functions below */ event LiquidatorChanged(address indexed Liquidator, bool newStatus); /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address account, address asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev KYC Integration */ /** * @dev Events to notify the frontend of all the functions below */ event KYCAdminChanged(address indexed KYCAdmin, bool newStatus); event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus); /** * @dev Function for use by the admin of the contract to add or remove KYC Admins */ function _changeKYCAdmin(address KYCAdmin, bool newStatus) public onlyOwner { KYCAdmins[KYCAdmin] = newStatus; emit KYCAdminChanged(KYCAdmin, newStatus); } /** * @dev Function for use by the KYC admins to add or remove KYC Customers */ function _changeCustomerKYC(address customer, bool newStatus) public { require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED"); customersWithKYC[customer] = newStatus; emit KYCCustomerChanged(customer, newStatus); } /** * @dev Liquidator Integration */ /** * @dev Function for use by the admin of the contract to add or remove Liquidators */ function _changeLiquidator(address liquidator, bool newStatus) public onlyOwner { liquidators[liquidator] = newStatus; emit LiquidatorChanged(liquidator, newStatus); } /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount( address asset, uint256 assetAmount, bool mulCollatRatio ) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } if (mulCollatRatio) { Exp memory scaledPrice; // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @param newCloseFactorMantissa new Close Factor, scaled by 1e18 * @param wethContractAddress WETH Contract Address * @param _rewardControl Reward Control Address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa, address wethContractAddress, address _rewardControl ) public onlyOwner returns (uint256) { // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; originationFee = Exp({mantissa: originationFeeMantissa}); closeFactorMantissa = newCloseFactorMantissa; require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() public { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public onlyOwner returns (uint256) { // Hard cap on the maximum number of markets allowed require( interestRateModel != address(0) && collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "INPUT_VALIDATION_FAILED" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public onlyOwner returns (uint256) { // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public onlyOwner returns (uint256) { // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public onlyOwner returns (uint256) { require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public onlyOwner returns (uint256) { // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint256 cash = getCash(asset); // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate(asset, cash - amount, markets[asset].totalSupply); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate(asset, cash - amount, markets[asset].totalBorrows); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH */ function supplyEther(uint256 etherAmount) internal returns (uint256) { require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR"); WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount, false ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent, false ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent, false ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, false, true); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(localResults.repayAmount); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED"); refreshAlkIndex(assetCollateral, targetAccount, true, true); refreshAlkIndex(assetCollateral, msg.sender, true, true); refreshAlkIndex(assetBorrow, targetAccount, false, true); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice revertIfError(err); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow revertIfError(err); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. revertIfError(err); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET revertIfError(err); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either revertIfError(err); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. revertIfError(err); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, false, true); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmount( asset, localResults.borrowAmountWithFee, true ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkIndex(asset, admin, true, true); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyReceived( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param user The address of the supplier/borrower to accrue rewards * @param isSupply Specifies if Supply or Borrow Index need to be updated * @param isVerified Verified / Public protocol */ function refreshAlkIndex( address market, address user, bool isSupply, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } if (isSupply) { rewardControl.refreshAlkSupplyIndex(market, user, isVerified); } else { rewardControl.refreshAlkBorrowIndex(market, user, isVerified); } } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/AlkemiEarnPublic.sol pragma solidity 0.4.24; contract AlkemiEarnPublic is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnPublic` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; defaultOriginationFee = (10**15); // default is 0.1% defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25 defaultLiquidationDiscount = (10**17); // default is 10% or 0.1 minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: defaultCollateralRatio}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount}); _guardCounter = 1; // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnPublic, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp supplyTotalValue; Exp sumSupplies; Exp borrowTotalValue; Exp sumBorrows; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a origination fee supply is received as admin * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyOrgFeeAsAdmin( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @dev emitted when new market is supported by admin */ event SupportedMarket( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters( uint256 oldCollateralRatioMantissa, uint256 newCollateralRatioMantissa, uint256 oldLiquidationDiscountMantissa, uint256 newLiquidationDiscountMantissa ); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee( uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint256) { return collateralMarkets.length; } /** * @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount(address asset, uint256 assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmountMulCollatRatio( address asset, uint256 assetAmount ) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK"); // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee( oldOriginationFee.mantissa, originationFeeMantissa ); closeFactorMantissa = newCloseFactorMantissa; return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK"); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Hard cap on the maximum number of markets allowed require( collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "Exceeding the max number of markets allowed" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK"); // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters( oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK" ); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK"); // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate( asset, getCash(asset) - amount, markets[asset].totalSupply ); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate( asset, getCash(asset) - amount, markets[asset].totalBorrows ); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Set WETH token contract address * @param wethContractAddress Enter the WETH token address */ function setWethAddress(address wethContractAddress) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED"); require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); return uint256(Error.NO_ERROR); } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function supplyEther(address user, uint256 etherAmount) internal returns (uint256) { user; // To silence the warning of unused local variable if (wethAddress != address(0)) { WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } else { return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR); } } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.sender, msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkBorrowIndex(asset, msg.sender, false); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther( msg.sender, localResults.repayAmount ); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(assetCollateral, targetAccount, false); refreshAlkSupplyIndex(assetCollateral, msg.sender, false); refreshAlkBorrowIndex(assetBorrow, targetAccount, false); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert(err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert(err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkBorrowIndex(asset, msg.sender, false); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmountMulCollatRatio( asset, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkSupplyIndex(asset, admin, false); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyOrgFeeAsAdmin( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants * @param _rewardControl The address of the underlying reward control contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function setRewardControlAddress(address _rewardControl) external returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED" ); require( address(rewardControl) != _rewardControl, "The same Reward Control address" ); require( _rewardControl != address(0), "RewardControl address cannot be empty" ); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); // success } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param supplier The address of the supplier to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified); } /** * @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market * @param market The address of the market to accrue rewards * @param borrower The address of the borrower to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified); } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/RewardControlStorage.sol pragma solidity 0.4.24; contract RewardControlStorage { struct MarketState { // @notice The market's last updated alkSupplyIndex or alkBorrowIndex uint224 index; // @notice The block number the index was last updated at uint32 block; } // @notice A list of all markets in the reward program mapped to respective verified/public protocols // @notice true => address[] represents Verified Protocol markets // @notice false => address[] represents Public Protocol markets mapping(bool => address[]) public allMarkets; // @notice The index for checking whether a market is already in the reward program // @notice The first mapping represents verified / public market and the second gives the existence of the market mapping(bool => mapping(address => bool)) public allMarketsIndex; // @notice The rate at which the Reward Control distributes ALK per block uint256 public alkRate; // @notice The portion of alkRate that each market currently receives // @notice The first mapping represents verified / public market and the second gives the alkSpeeds mapping(bool => mapping(address => uint256)) public alkSpeeds; // @notice The ALK market supply state for each market // @notice The first mapping represents verified / public market and the second gives the supplyState mapping(bool => mapping(address => MarketState)) public alkSupplyState; // @notice The ALK market borrow state for each market // @notice The first mapping represents verified / public market and the second gives the borrowState mapping(bool => mapping(address => MarketState)) public alkBorrowState; // @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK // @notice verified/public => market => supplier => supplierIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkSupplierIndex; // @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK // @notice verified/public => market => borrower => borrowerIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkBorrowerIndex; // @notice The ALK accrued but not yet transferred to each participant mapping(address => uint256) public alkAccrued; // @notice To make sure initializer is called only once bool public initializationDone; // @notice The address of the current owner of this contract address public owner; // @notice The proposed address of the new owner of this contract address public newOwner; // @notice The underlying AlkemiEarnVerified contract AlkemiEarnVerified public alkemiEarnVerified; // @notice The underlying AlkemiEarnPublic contract AlkemiEarnPublic public alkemiEarnPublic; // @notice The ALK token address address public alkAddress; // Hard cap on the maximum number of markets uint8 public MAXIMUM_NUMBER_OF_MARKETS; } // File: contracts/ExponentialNoError.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/RewardControl.sol pragma solidity 0.4.24; contract RewardControl is RewardControlStorage, RewardControlInterface, ExponentialNoError { /** * Events */ /// @notice Emitted when a new ALK speed is calculated for a market event AlkSpeedUpdated( address indexed market, uint256 newSpeed, bool isVerified ); /// @notice Emitted when ALK is distributed to a supplier event DistributedSupplierAlk( address indexed market, address indexed supplier, uint256 supplierDelta, uint256 supplierAccruedAlk, uint256 supplyIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is distributed to a borrower event DistributedBorrowerAlk( address indexed market, address indexed borrower, uint256 borrowerDelta, uint256 borrowerAccruedAlk, uint256 borrowIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is transferred to a participant event TransferredAlk( address indexed participant, uint256 participantAccrued, address market, bool isVerified ); /// @notice Emitted when the owner of the contract is updated event OwnerUpdate(address indexed owner, address indexed newOwner); /// @notice Emitted when a market is added event MarketAdded( address indexed market, uint256 numberOfMarkets, bool isVerified ); /// @notice Emitted when a market is removed event MarketRemoved( address indexed market, uint256 numberOfMarkets, bool isVerified ); /** * Constants */ /** * Constructor */ /** * @notice `RewardControl` is the contract to calculate and distribute reward tokens * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer( address _owner, address _alkemiEarnVerified, address _alkemiEarnPublic, address _alkAddress ) public { require( _owner != address(0) && _alkemiEarnVerified != address(0) && _alkemiEarnPublic != address(0) && _alkAddress != address(0), "Inputs cannot be 0x00" ); if (initializationDone == false) { initializationDone = true; owner = _owner; alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); alkAddress = _alkAddress; // Total Liquidity rewards for 4 years = 70,000,000 // Liquidity per year = 70,000,000/4 = 17,500,000 // Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000 // 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing) alkRate = 3690226761271430000; MAXIMUM_NUMBER_OF_MARKETS = 16; } } /** * Modifiers */ /** * @notice Make sure that the sender is only the owner of the contract */ modifier onlyOwner() { require(msg.sender == owner, "non-owner"); _; } /** * Public functions */ /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, supplier, isVerified); } /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, borrower, isVerified); } /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external { claimAlk(holder, allMarkets[true], true); claimAlk(holder, allMarkets[false], false); } /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Specifies if the market is from verified or public protocol */ function claimAlk( address holder, address market, bool isVerified ) external { require(allMarketsIndex[isVerified][market], "Market does not exist"); address[] memory markets = new address[](1); markets[0] = market; claimAlk(holder, markets, isVerified); } /** * Private functions */ /** * @notice Recalculate and update ALK speeds for all markets */ function refreshMarketLiquidity() internal view returns (Exp[] memory, Exp memory) { Exp memory totalLiquidity = Exp({mantissa: 0}); Exp[] memory marketTotalLiquidity = new Exp[]( add_(allMarkets[true].length, allMarkets[false].length) ); address currentMarket; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; uint256 currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); uint256 currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); Exp memory currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[i] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[ verifiedMarketsLength + j ] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } return (marketTotalLiquidity, totalLiquidity); } /** * @notice Recalculate and update ALK speeds for all markets */ function refreshAlkSpeeds() public { address currentMarket; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 newSpeed; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; alkSpeeds[true][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, true); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; newSpeed = totalLiquidity.mantissa > 0 ? mul_( alkRate, div_( marketTotalLiquidity[verifiedMarketsLength + j], totalLiquidity ) ) : 0; alkSpeeds[false][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, false); } } /** * @notice Accrue ALK to the market by updating the supply index * @param market The market whose supply index to update * @param isVerified Verified / Public protocol */ function updateAlkSupplyIndex(address market, bool isVerified) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalSupply = getMarketTotalSupply( market, isVerified ); uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalSupply > 0 ? fraction(supplyAlkAccrued, marketTotalSupply) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: supplyState.index}), ratio ); alkSupplyState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Accrue ALK to the market by updating the borrow index * @param market The market whose borrow index to update * @param isVerified Verified / Public protocol */ function updateAlkBorrowIndex(address market, bool isVerified) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalBorrows = getMarketTotalBorrows( market, isVerified ); uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalBorrows > 0 ? fraction(borrowAlkAccrued, marketTotalBorrows) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: borrowState.index}), ratio ); alkBorrowState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier] * @param market The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeSupplierAlk( address market, address supplier, bool isVerified ) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: alkSupplierIndex[isVerified][market][supplier] }); alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa > 0) { Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierBalance = getSupplyBalance( market, supplier, isVerified ); uint256 supplierDelta = mul_(supplierBalance, deltaIndex); alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta); emit DistributedSupplierAlk( market, supplier, supplierDelta, alkAccrued[supplier], supplyIndex.mantissa, isVerified ); } } /** * @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower] * @param market The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeBorrowerAlk( address market, address borrower, bool isVerified ) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: alkBorrowerIndex[isVerified][market][borrower] }); alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerBalance = getBorrowBalance( market, borrower, isVerified ); uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex); alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta); emit DistributedBorrowerAlk( market, borrower, borrowerDelta, alkAccrued[borrower], borrowIndex.mantissa, isVerified ); } } /** * @notice Claim all the ALK accrued by holder in the specified markets * @param holder The address to claim ALK for * @param markets The list of markets to claim ALK in * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address[] memory markets, bool isVerified ) internal { for (uint256 i = 0; i < markets.length; i++) { address market = markets[i]; updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, holder, isVerified); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, holder, isVerified); alkAccrued[holder] = transferAlk( holder, alkAccrued[holder], market, isVerified ); } } /** * @notice Transfer ALK to the participant * @dev Note: If there is not enough ALK, we do not perform the transfer all. * @param participant The address of the participant to transfer ALK to * @param participantAccrued The amount of ALK to (possibly) transfer * @param market Market for which ALK is transferred * @param isVerified Verified / Public Protocol * @return The amount of ALK which was NOT transferred to the participant */ function transferAlk( address participant, uint256 participantAccrued, address market, bool isVerified ) internal returns (uint256) { if (participantAccrued > 0) { EIP20Interface alk = EIP20Interface(getAlkAddress()); uint256 alkRemaining = alk.balanceOf(address(this)); if (participantAccrued <= alkRemaining) { alk.transfer(participant, participantAccrued); emit TransferredAlk( participant, participantAccrued, market, isVerified ); return 0; } } return participantAccrued; } /** * Getters */ /** * @notice Get the current block number * @return The current block number */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Get the current accrued ALK for a participant * @param participant The address of the participant * @return The amount of accrued ALK for the participant */ function getAlkAccrued(address participant) public view returns (uint256) { return alkAccrued[participant]; } /** * @notice Get the address of the ALK token * @return The address of ALK token */ function getAlkAddress() public view returns (address) { return alkAddress; } /** * @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract * @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract */ function getAlkemiEarnAddress() public view returns (address, address) { return (address(alkemiEarnVerified), address(alkemiEarnPublic)); } /** * @notice Get market statistics from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market statistics for the given market */ function getMarketStats(address market, bool isVerified) public view returns ( bool isSupported, uint256 blockNumber, address interestRateModel, uint256 totalSupply, uint256 supplyRateMantissa, uint256 supplyIndex, uint256 totalBorrows, uint256 borrowRateMantissa, uint256 borrowIndex ) { if (isVerified) { return (alkemiEarnVerified.markets(market)); } else { return (alkemiEarnPublic.markets(market)); } } /** * @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total supply for the given market */ function getMarketTotalSupply(address market, bool isVerified) public view returns (uint256) { uint256 totalSupply; (, , , totalSupply, , , , , ) = getMarketStats(market, isVerified); return totalSupply; } /** * @notice Get market total borrows from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total borrows for the given market */ function getMarketTotalBorrows(address market, bool isVerified) public view returns (uint256) { uint256 totalBorrows; (, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified); return totalBorrows; } /** * @notice Get supply balance of the specified market and supplier * @param market The address of the market * @param supplier The address of the supplier * @param isVerified Verified / Public protocol * @return Supply balance of the specified market and supplier */ function getSupplyBalance( address market, address supplier, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getSupplyBalance(supplier, market); } else { return alkemiEarnPublic.getSupplyBalance(supplier, market); } } /** * @notice Get borrow balance of the specified market and borrower * @param market The address of the market * @param borrower The address of the borrower * @param isVerified Verified / Public protocol * @return Borrow balance of the specified market and borrower */ function getBorrowBalance( address market, address borrower, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getBorrowBalance(borrower, market); } else { return alkemiEarnPublic.getBorrowBalance(borrower, market); } } /** * Admin functions */ /** * @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != owner, "TransferOwnership: the same owner."); newOwner = _newOwner; } /** * @notice Accept the ownership of this contract by the new owner */ function acceptOwnership() external { require( msg.sender == newOwner, "AcceptOwnership: only new owner do this." ); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } /** * @notice Add new market to the reward program * @param market The address of the new market to be added to the reward program * @param isVerified Verified / Public protocol */ function addMarket(address market, bool isVerified) external onlyOwner { require(!allMarketsIndex[isVerified][market], "Market already exists"); require( allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS), "Exceeding the max number of markets allowed" ); allMarketsIndex[isVerified][market] = true; allMarkets[isVerified].push(market); emit MarketAdded( market, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Remove a market from the reward program based on array index * @param id The index of the `allMarkets` array to be removed * @param isVerified Verified / Public protocol */ function removeMarket(uint256 id, bool isVerified) external onlyOwner { if (id >= allMarkets[isVerified].length) { return; } allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false; address removedMarket = allMarkets[isVerified][id]; for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) { allMarkets[isVerified][i] = allMarkets[isVerified][i + 1]; } allMarkets[isVerified].length--; // reset the ALK speeds for the removed market and refresh ALK speeds alkSpeeds[isVerified][removedMarket] = 0; refreshAlkSpeeds(); emit MarketRemoved( removedMarket, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Set ALK token address * @param _alkAddress The ALK token address */ function setAlkAddress(address _alkAddress) external onlyOwner { require(alkAddress != _alkAddress, "The same ALK address"); require(_alkAddress != address(0), "ALK address cannot be empty"); alkAddress = _alkAddress; } /** * @notice Set AlkemiEarnVerified contract address * @param _alkemiEarnVerified The AlkemiEarnVerified contract address */ function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified) external onlyOwner { require( address(alkemiEarnVerified) != _alkemiEarnVerified, "The same AlkemiEarnVerified address" ); require( _alkemiEarnVerified != address(0), "AlkemiEarnVerified address cannot be empty" ); alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); } /** * @notice Set AlkemiEarnPublic contract address * @param _alkemiEarnPublic The AlkemiEarnVerified contract address */ function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); } /** * @notice Set ALK rate * @param _alkRate The ALK rate */ function setAlkRate(uint256 _alkRate) external onlyOwner { alkRate = _alkRate; } /** * @notice Get latest ALK rewards * @param user the supplier/borrower */ function getAlkRewards(address user) external view returns (uint256) { // Refresh ALK speeds uint256 alkRewards = alkAccrued[user]; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ) ) ); } for (uint256 j = 0; j < allMarkets[false].length; j++) { uint256 index = verifiedMarketsLength + j; alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ) ) ); } return alkRewards; } /** * @notice Get latest Supply ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the supplier * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getSupplyAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory supplyState = alkSupplyState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(supplyState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: supplyState.index}), ( getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(supplyState.block) ), newSpeed ), getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); supplyState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) { supplyState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnVerified.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( !isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnPublic.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } /** * @notice Get latest Borrow ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the borrower * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getBorrowAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory borrowState = alkBorrowState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(borrowState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: borrowState.index}), ( getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(borrowState.block) ), newSpeed ), getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); borrowState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) { borrowState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && isVerified ) { return mul_( alkemiEarnVerified.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && !isVerified ) { return mul_( alkemiEarnPublic.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } }
Set AlkemiEarnPublic contract address _alkemiEarnPublic The AlkemiEarnVerified contract address/
function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); }
81,725
//Address: 0xC6D23c746d9b3d97D8281BD878A17CdFA90a9ac1 //Contract name: CustomPOAToken //Balance: 0.0007065 Ether //Verification Date: 3/29/2018 //Transacion Count: 37 // CODE STARTS HERE 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/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 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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; } } // File: zeppelin-solidity/contracts/token/PausableToken.sol /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/CustomPOAToken.sol contract CustomPOAToken is PausableToken { string public name; string public symbol; uint8 public constant decimals = 18; address public owner; address public broker; address public custodian; uint256 public creationBlock; uint256 public timeoutBlock; // the total per token payout rate: accumulates as payouts are received uint256 public totalPerTokenPayout; uint256 public tokenSaleRate; uint256 public fundedAmount; uint256 public fundingGoal; uint256 public initialSupply; // ‰ permille NOT percent uint256 public constant feeRate = 5; // self contained whitelist on contract, must be whitelisted to buy mapping (address => bool) public whitelisted; // used to deduct already claimed payouts on a per token basis mapping(address => uint256) public claimedPerTokenPayouts; // fallback for when a transfer happens with payouts remaining mapping(address => uint256) public unclaimedPayoutTotals; enum Stages { Funding, Pending, Failed, Active, Terminated } Stages public stage = Stages.Funding; event StageEvent(Stages stage); event BuyEvent(address indexed buyer, uint256 amount); event PayoutEvent(uint256 amount); event ClaimEvent(uint256 payout); event TerminatedEvent(); event WhitelistedEvent(address indexed account, bool isWhitelisted); modifier isWhitelisted() { require(whitelisted[msg.sender]); _; } modifier onlyCustodian() { require(msg.sender == custodian); _; } // start stage related modifiers modifier atStage(Stages _stage) { require(stage == _stage); _; } modifier atEitherStage(Stages _stage, Stages _orStage) { require(stage == _stage || stage == _orStage); _; } modifier checkTimeout() { if (stage == Stages.Funding && block.number >= creationBlock.add(timeoutBlock)) { uint256 _unsoldBalance = balances[this]; balances[this] = 0; totalSupply = totalSupply.sub(_unsoldBalance); Transfer(this, address(0), balances[this]); enterStage(Stages.Failed); } _; } // end stage related modifiers // token totalSupply must be more than fundingGoal! function CustomPOAToken ( string _name, string _symbol, address _broker, address _custodian, uint256 _timeoutBlock, uint256 _totalSupply, uint256 _fundingGoal ) public { require(_fundingGoal > 0); require(_totalSupply > _fundingGoal); owner = msg.sender; name = _name; symbol = _symbol; broker = _broker; custodian = _custodian; timeoutBlock = _timeoutBlock; creationBlock = block.number; // essentially sqm unit of building... totalSupply = _totalSupply; initialSupply = _totalSupply; fundingGoal = _fundingGoal; balances[this] = _totalSupply; paused = true; } // start token conversion functions /******************* * TKN supply * * --- = ------- * * ETH funding * *******************/ // util function to convert wei to tokens. can be used publicly to see // what the balance would be for a given Ξ amount. // will drop miniscule amounts of wei due to integer division function weiToTokens(uint256 _weiAmount) public view returns (uint256) { return _weiAmount .mul(1e18) .mul(initialSupply) .div(fundingGoal) .div(1e18); } // util function to convert tokens to wei. can be used publicly to see how // much Ξ would be received for token reclaim amount // will typically lose 1 wei unit of Ξ due to integer division function tokensToWei(uint256 _tokenAmount) public view returns (uint256) { return _tokenAmount .mul(1e18) .mul(fundingGoal) .div(initialSupply) .div(1e18); } // end token conversion functions // pause override function unpause() public onlyOwner whenPaused { // only allow unpausing when in Active stage require(stage == Stages.Active); return super.unpause(); } // stage related functions function enterStage(Stages _stage) private { stage = _stage; StageEvent(_stage); } // start whitelist related functions // allow address to buy tokens function whitelistAddress(address _address) external onlyOwner atStage(Stages.Funding) { require(whitelisted[_address] != true); whitelisted[_address] = true; WhitelistedEvent(_address, true); } // disallow address to buy tokens. function blacklistAddress(address _address) external onlyOwner atStage(Stages.Funding) { require(whitelisted[_address] != false); whitelisted[_address] = false; WhitelistedEvent(_address, false); } // check to see if contract whitelist has approved address to buy function whitelisted(address _address) public view returns (bool) { return whitelisted[_address]; } // end whitelist related functions // start fee handling functions // public utility function to allow checking of required fee for a given amount function calculateFee(uint256 _value) public view returns (uint256) { return feeRate.mul(_value).div(1000); } // end fee handling functions // start lifecycle functions function buy() public payable checkTimeout atStage(Stages.Funding) isWhitelisted returns (bool) { uint256 _payAmount; uint256 _buyAmount; // check if balance has met funding goal to move on to Pending if (fundedAmount.add(msg.value) < fundingGoal) { // _payAmount is just value sent _payAmount = msg.value; // get token amount from wei... drops remainders (keeps wei dust in contract) _buyAmount = weiToTokens(_payAmount); // check that buyer will indeed receive something after integer division // this check cannot be done in other case because it could prevent // contract from moving to next stage require(_buyAmount > 0); } else { // let the world know that the token is in Pending Stage enterStage(Stages.Pending); // set refund amount (overpaid amount) uint256 _refundAmount = fundedAmount.add(msg.value).sub(fundingGoal); // get actual Ξ amount to buy _payAmount = msg.value.sub(_refundAmount); // get token amount from wei... drops remainders (keeps wei dust in contract) _buyAmount = weiToTokens(_payAmount); // assign remaining dust uint256 _dust = balances[this].sub(_buyAmount); // sub dust from contract balances[this] = balances[this].sub(_dust); // give dust to owner balances[owner] = balances[owner].add(_dust); Transfer(this, owner, _dust); // SHOULD be ok even with reentrancy because of enterStage(Stages.Pending) msg.sender.transfer(_refundAmount); } // deduct token buy amount balance from contract balance balances[this] = balances[this].sub(_buyAmount); // add token buy amount to sender's balance balances[msg.sender] = balances[msg.sender].add(_buyAmount); // increment the funded amount fundedAmount = fundedAmount.add(_payAmount); // send out event giving info on amount bought as well as claimable dust Transfer(this, msg.sender, _buyAmount); BuyEvent(msg.sender, _buyAmount); return true; } function activate() external checkTimeout onlyCustodian payable atStage(Stages.Pending) returns (bool) { // calculate company fee charged for activation uint256 _fee = calculateFee(fundingGoal); // value must exactly match fee require(msg.value == _fee); // if activated and fee paid: put in Active stage enterStage(Stages.Active); // owner (company) fee set in unclaimedPayoutTotals to be claimed by owner unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee); // custodian value set to claimable. can now be claimed via claim function // set all eth in contract other than fee as claimable. // should only be buy()s. this ensures buy() dust is cleared unclaimedPayoutTotals[custodian] = unclaimedPayoutTotals[custodian] .add(this.balance.sub(_fee)); // allow trading of tokens paused = false; // let world know that this token can now be traded. Unpause(); return true; } // used when property no longer exists etc. allows for winding down via payouts // can no longer be traded after function is run function terminate() external onlyCustodian atStage(Stages.Active) returns (bool) { // set Stage to terminated enterStage(Stages.Terminated); // pause. Cannot be unpaused now that in Stages.Terminated paused = true; // let the world know this token is in Terminated Stage TerminatedEvent(); } // emergency temporary function used only in case of emergency to return // Ξ to contributors in case of catastrophic contract failure. function kill() external onlyOwner { // stop trading paused = true; // enter stage which will no longer allow unpausing enterStage(Stages.Terminated); // transfer funds to company in order to redistribute manually owner.transfer(this.balance); // let the world know that this token is in Terminated Stage TerminatedEvent(); } // end lifecycle functions // start payout related functions // get current payout for perTokenPayout and unclaimed function currentPayout(address _address, bool _includeUnclaimed) public view returns (uint256) { /* need to check if there have been no payouts safe math will throw otherwise due to dividing 0 The below variable represents the total payout from the per token rate pattern it uses this funky naming pattern in order to differentiate from the unclaimedPayoutTotals which means something very different. */ uint256 _totalPerTokenUnclaimedConverted = totalPerTokenPayout == 0 ? 0 : balances[_address] .mul(totalPerTokenPayout.sub(claimedPerTokenPayouts[_address])) .div(1e18); /* balances may be bumped into unclaimedPayoutTotals in order to maintain balance tracking accross token transfers perToken payout rates are stored * 1e18 in order to be kept accurate perToken payout is / 1e18 at time of usage for actual Ξ balances unclaimedPayoutTotals are stored as actual Ξ value no need for rate * balance */ return _includeUnclaimed ? _totalPerTokenUnclaimedConverted.add(unclaimedPayoutTotals[_address]) : _totalPerTokenUnclaimedConverted; } // settle up perToken balances and move into unclaimedPayoutTotals in order // to ensure that token transfers will not result in inaccurate balances function settleUnclaimedPerTokenPayouts(address _from, address _to) private returns (bool) { // add perToken balance to unclaimedPayoutTotals which will not be affected by transfers unclaimedPayoutTotals[_from] = unclaimedPayoutTotals[_from].add(currentPayout(_from, false)); // max out claimedPerTokenPayouts in order to effectively make perToken balance 0 claimedPerTokenPayouts[_from] = totalPerTokenPayout; // same as above for to unclaimedPayoutTotals[_to] = unclaimedPayoutTotals[_to].add(currentPayout(_to, false)); // same as above for to claimedPerTokenPayouts[_to] = totalPerTokenPayout; return true; } // used to manually set Stage to Failed when no users have bought any tokens // if no buy()s occurred before timeoutBlock token would be stuck in Funding function setFailed() external atStage(Stages.Funding) checkTimeout returns (bool) { if (stage == Stages.Funding) { revert(); } return true; } // reclaim Ξ for sender if fundingGoal is not met within timeoutBlock function reclaim() external checkTimeout atStage(Stages.Failed) returns (bool) { // get token balance of user uint256 _tokenBalance = balances[msg.sender]; // ensure that token balance is over 0 require(_tokenBalance > 0); // set token balance to 0 so re reclaims are not possible balances[msg.sender] = 0; // decrement totalSupply by token amount being reclaimed totalSupply = totalSupply.sub(_tokenBalance); Transfer(msg.sender, address(0), _tokenBalance); // decrement fundedAmount by eth amount converted from token amount being reclaimed fundedAmount = fundedAmount.sub(tokensToWei(_tokenBalance)); // set reclaim total as token value uint256 _reclaimTotal = tokensToWei(_tokenBalance); // send Ξ back to sender msg.sender.transfer(_reclaimTotal); return true; } // send Ξ to contract to be claimed by token holders function payout() external payable atEitherStage(Stages.Active, Stages.Terminated) onlyCustodian returns (bool) { // calculate fee based on feeRate uint256 _fee = calculateFee(msg.value); // ensure the value is high enough for a fee to be claimed require(_fee > 0); // deduct fee from payout uint256 _payoutAmount = msg.value.sub(_fee); /* totalPerTokenPayout is a rate at which to payout based on token balance it is stored as * 1e18 in order to keep accuracy it is / 1e18 when used relating to actual Ξ values */ totalPerTokenPayout = totalPerTokenPayout .add(_payoutAmount .mul(1e18) .div(totalSupply) ); // take remaining dust and send to owner rather than leave stuck in contract // should not be more than a few wei uint256 _delta = (_payoutAmount.mul(1e18) % totalSupply).div(1e18); unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee).add(_delta); // let the world know that a payout has happened for this token PayoutEvent(_payoutAmount); return true; } // claim total Ξ claimable for sender based on token holdings at time of each payout function claim() external atEitherStage(Stages.Active, Stages.Terminated) returns (uint256) { /* pass true to currentPayout in order to get both: perToken payouts unclaimedPayoutTotals */ uint256 _payoutAmount = currentPayout(msg.sender, true); // check that there indeed is a pending payout for sender require(_payoutAmount > 0); // max out per token payout for sender in order to make payouts effectively // 0 for sender claimedPerTokenPayouts[msg.sender] = totalPerTokenPayout; // 0 out unclaimedPayoutTotals for user unclaimedPayoutTotals[msg.sender] = 0; // let the world know that a payout for sender has been claimed ClaimEvent(_payoutAmount); // transfer Ξ payable amount to sender msg.sender.transfer(_payoutAmount); return _payoutAmount; } // end payout related functions // start ERC20 overrides // same as ERC20 transfer other than settling unclaimed payouts function transfer ( address _to, uint256 _value ) public whenNotPaused returns (bool) { // move perToken payout balance to unclaimedPayoutTotals require(settleUnclaimedPerTokenPayouts(msg.sender, _to)); return super.transfer(_to, _value); } // same as ERC20 transfer other than settling unclaimed payouts function transferFrom ( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { // move perToken payout balance to unclaimedPayoutTotals require(settleUnclaimedPerTokenPayouts(_from, _to)); return super.transferFrom(_from, _to, _value); } // end ERC20 overrides // check if there is a way to get around gas issue when no gas limit calculated... // fallback function defaulting to buy function() public payable { buy(); } }
same as ERC20 transfer other than settling unclaimed payouts move perToken payout balance to unclaimedPayoutTotals
function transferFrom ( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { require(settleUnclaimedPerTokenPayouts(_from, _to)); return super.transferFrom(_from, _to, _value); }
12,650,393
//Address: 0x8c7d36631768c83feae33ec42a843cc2a2fa1897 //Contract name: GoldRaffle //Balance: 0.705 Ether //Verification Date: 2/6/2018 //Transacion Count: 30 // CODE STARTS HERE pragma solidity ^0.4.18; contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } library OraclizeLib { struct OraclizeData { OraclizeAddrResolverI oraclizeAddressResolver; OraclizeI oraclize; mapping(bytes32=>bytes32) oraclizeRandomDSArgs; mapping(bytes32=>bool) oraclizeRandomDsSessionKeyHashVerified; string oraclizeNetworkName; } function initializeOraclize(OraclizeData storage self) internal { self.oraclizeAddressResolver = oraclize_setNetwork(self); if (self.oraclizeAddressResolver != address(0)) { self.oraclize = OraclizeI(self.oraclizeAddressResolver.getAddress()); } } function oraclize_setNetwork(OraclizeData storage self) public returns(OraclizeAddrResolverI) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0) { //mainnet oraclize_setNetworkName(self, "eth_mainnet"); return OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0) { //ropsten testnet oraclize_setNetworkName(self, "eth_ropsten3"); return OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0) { //kovan testnet oraclize_setNetworkName(self, "eth_kovan"); return OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0) { //rinkeby testnet oraclize_setNetworkName(self, "eth_rinkeby"); return OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0) { //ethereum-bridge return OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0) { //ether.camp ide return OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0) { //browser-solidity return OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); } } function oraclize_setNetworkName(OraclizeData storage self, string _network_name) internal { self.oraclizeNetworkName = _network_name; } function oraclize_getNetworkName(OraclizeData storage self) internal constant returns (string) { return self.oraclizeNetworkName; } function oraclize_getPrice(OraclizeData storage self, string datasource) public returns (uint) { return self.oraclize.getPrice(datasource); } function oraclize_getPrice(OraclizeData storage self, string datasource, uint gaslimit) public returns (uint) { return self.oraclize.getPrice(datasource, gaslimit); } function oraclize_query(OraclizeData storage self, string datasource, string arg) public returns (bytes32 id) { return oraclize_query(self, 0, datasource, arg); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string arg) public returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) { return 0; // unexpectedly high price } return self.oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(OraclizeData storage self, string datasource, string arg, uint gaslimit) public returns (bytes32 id) { return oraclize_query(self, 0, datasource, arg, gaslimit); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string arg, uint gaslimit) public returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) { return 0; // unexpectedly high price } return self.oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(OraclizeData storage self, string datasource, string arg1, string arg2) public returns (bytes32 id) { return oraclize_query(self, 0, datasource, arg1, arg2); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string arg1, string arg2) public returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) { return 0; // unexpectedly high price } return self.oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(OraclizeData storage self, string datasource, string arg1, string arg2, uint gaslimit) public returns (bytes32 id) { return oraclize_query(self, 0, datasource, arg1, arg2, gaslimit); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) public returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) { return 0; // unexpectedly high price } return self.oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(OraclizeData storage self, string datasource, string[] argN) internal returns (bytes32 id) { return oraclize_query(self, 0, datasource, argN); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string[] argN) internal returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) { return 0; // unexpectedly high price } bytes memory args = stra2cbor(argN); return self.oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(OraclizeData storage self, string datasource, string[] argN, uint gaslimit) internal returns (bytes32 id) { return oraclize_query(self, 0, datasource, argN, gaslimit); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string[] argN, uint gaslimit) internal returns (bytes32 id){ uint price = self.oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) { return 0; // unexpectedly high price } bytes memory args = stra2cbor(argN); return self.oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, bytes[] argN, uint gaslimit) internal returns (bytes32 id){ uint price = self.oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) { return 0; // unexpectedly high price } bytes memory args = ba2cbor(argN); return self.oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_newRandomDSQuery(OraclizeData storage self, uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32) { assert((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(self); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[] memory args = new bytes[](3); args[0] = unonce; args[1] = nbytes; args[2] = sessionKeyHash; bytes32 queryId = oraclize_query(self, _delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(self, queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_proofVerify__main(OraclizeData storage self, bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (keccak256(keyhash) == keccak256(sha256(context_name, queryId))); if (checkok == false) { return false; } bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) { return false; } // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (self.oraclizeRandomDSArgs[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)) { delete self.oraclizeRandomDSArgs[queryId]; //unonce, nbytes and sessionKeyHash match } else { return false; } // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) { return false; } // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (self.oraclizeRandomDsSessionKeyHashVerified[sessionPubkeyHash] == false) { self.oraclizeRandomDsSessionKeyHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return self.oraclizeRandomDsSessionKeyHashVerified[sessionPubkeyHash]; } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) { return false; } // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(OraclizeData storage self, bytes32 _queryId, string _result, bytes _proof) internal returns (uint8) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(self, _proof, _queryId, bytes(_result), oraclize_getNetworkName(self)); if (proofVerified == false) { return 2; } return 0; } function oraclize_randomDS_setCommitment(OraclizeData storage self, bytes32 queryId, bytes32 commitment) internal { self.oraclizeRandomDSArgs[queryId] = commitment; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal pure returns (bool) { bool match_ = true; for (uint i=0; i<prefix.length; i++) { if (content[i] != prefix[i]) { match_ = false; } } return match_; } function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function oraclize_cbAddress(OraclizeData storage self) public constant returns (address) { return self.oraclize.cbAddress(); } function oraclize_setProof(OraclizeData storage self, byte proofP) public { return self.oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(OraclizeData storage self, uint gasPrice) public { return self.oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(OraclizeData storage self, bytes32 config) public { return self.oraclize.setConfig(config); } function getCodeSize(address _addr) public constant returns(uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_randomDS_getSessionPubKeyHash(OraclizeData storage self) internal returns (bytes32){ return self.oraclize.randomDS_getSessionPubKeyHash(); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; assert (to.length >= minLength); // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } } library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract RewardDistributable { event TokensRewarded(address indexed player, address rewardToken, uint rewards, address requester, uint gameId, uint block); event ReferralRewarded(address indexed referrer, address indexed player, address rewardToken, uint rewards, uint gameId, uint block); event ReferralRegistered(address indexed player, address indexed referrer); /// @dev Calculates and transfers the rewards to the player. function transferRewards(address player, uint entryAmount, uint gameId) public; /// @dev Returns the total number of tokens, across all approvals. function getTotalTokens(address tokenAddress) public constant returns(uint); /// @dev Returns the total number of supported reward token contracts. function getRewardTokenCount() public constant returns(uint); /// @dev Gets the total number of approvers. function getTotalApprovers() public constant returns(uint); /// @dev Gets the reward rate inclusive of referral bonus. function getRewardRate(address player, address tokenAddress) public constant returns(uint); /// @dev Adds a requester to the whitelist. /// @param requester The address of a contract which will request reward transfers function addRequester(address requester) public; /// @dev Removes a requester from the whitelist. /// @param requester The address of a contract which will request reward transfers function removeRequester(address requester) public; /// @dev Adds a approver address. Approval happens with the token contract. /// @param approver The approver address to add to the pool. function addApprover(address approver) public; /// @dev Removes an approver address. /// @param approver The approver address to remove from the pool. function removeApprover(address approver) public; /// @dev Updates the reward rate function updateRewardRate(address tokenAddress, uint newRewardRate) public; /// @dev Updates the token address of the payment type. function addRewardToken(address tokenAddress, uint newRewardRate) public; /// @dev Updates the token address of the payment type. function removeRewardToken(address tokenAddress) public; /// @dev Updates the referral bonus rate function updateReferralBonusRate(uint newReferralBonusRate) public; /// @dev Registers the player with the given referral code /// @param player The address of the player /// @param referrer The address of the referrer function registerReferral(address player, address referrer) public; /// @dev Transfers any tokens to the owner function destroyRewards() public; } contract Priceable { modifier costsExactly(uint price) { if (msg.value == price) { _; } } modifier costs(uint price) { if (msg.value >= price) { _; } } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; 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; } } contract Cascading is Ownable { using SafeMath for uint256; struct Cascade { address cascade; uint16 percentage; } uint public totalCascadingPercentage; Cascade[] public cascades; /// @dev Adds an address and associated percentage for transfer. /// @param newAddress The new address function addCascade(address newAddress, uint newPercentage) public onlyOwner { cascades.push(Cascade(newAddress, uint16(newPercentage))); totalCascadingPercentage += newPercentage; } /// @dev Deletes an address and associated percentage at the given index. /// @param index The index of the cascade to be deleted. function deleteCascade(uint index) public onlyOwner { require(index < cascades.length); totalCascadingPercentage -= cascades[index].percentage; cascades[index] = cascades[cascades.length - 1]; delete cascades[cascades.length - 1]; cascades.length--; } /// @dev Transfers the cascade values to the assigned addresses /// @param totalJackpot the total jackpot amount function transferCascades(uint totalJackpot) internal { for (uint i = 0; i < cascades.length; i++) { uint cascadeTotal = getCascadeTotal(cascades[i].percentage, totalJackpot); // Should be safe from re-entry given gas limit of 2300. cascades[i].cascade.transfer(cascadeTotal); } } /// @dev Gets the cascade total for the given percentage /// @param percentage the percentage of the total pot as a uint /// @param totalJackpot the total jackpot amount /// @return the total amount the percentage represents function getCascadeTotal(uint percentage, uint totalJackpot) internal pure returns(uint) { return totalJackpot.mul(percentage).div(100); } /// A utility method to calculate the total after cascades have been applied. /// @param totalJackpot the total jackpot amount /// @return the total amount after the cascades have been applied function getTotalAfterCascades(uint totalJackpot) internal constant returns (uint) { uint cascadeTotal = getCascadeTotal(totalCascadingPercentage, totalJackpot); return totalJackpot.sub(cascadeTotal); } } contract SafeWinner is Ownable { using SafeMath for uint256; mapping(address => uint) public pendingPayments; address[] public pendingWinners; uint public totalPendingPayments; event WinnerWithdrew(address indexed winner, uint amount, uint block); /// @dev records the winner so that a transfer or withdraw can occur at /// a later date. function addPendingWinner(address winner, uint amount) internal { pendingPayments[winner] = pendingPayments[winner].add(amount); totalPendingPayments = totalPendingPayments.add(amount); pendingWinners.push(winner); } /// @dev allows a winner to withdraw their rightful jackpot. function withdrawWinnings() public { address winner = msg.sender; uint payment = pendingPayments[winner]; require(payment > 0); require(this.balance >= payment); transferPending(winner, payment); } /// @dev Retries all pending winners function retryWinners() public onlyOwner { for (uint i = 0; i < pendingWinners.length; i++) { retryWinner(i); } pendingWinners.length = 0; } function retryWinner(uint index) public onlyOwner { address winner = pendingWinners[index]; uint payment = pendingPayments[winner]; require(this.balance >= payment); if (payment != 0) { transferPending(winner, payment); } } function transferPending(address winner, uint256 payment) internal { totalPendingPayments = totalPendingPayments.sub(payment); pendingPayments[winner] = 0; winner.transfer(payment); WinnerWithdrew(winner, payment, block.number); } } contract Raffle is Ownable, Priceable, SafeWinner, Cascading { using SafeMath for uint256; using OraclizeLib for OraclizeLib.OraclizeData; enum RaffleState { Active, InActive, PendingInActive } enum RandomSource { RandomDS, Qrng } struct Jackpot { uint absoluteTotal; uint feeTotal; uint cascadeTotal; uint winnerTotal; } struct TicketHolder { address purchaser; uint16 count; uint80 runningTotal; } // public RaffleState public raffleState; RandomSource public randomSource; uint public ticketPrice; uint public gameId; uint public fee; // internal TicketHolder[] internal ticketHolders; uint internal randomBytes; uint internal randomQueried; uint internal callbackGas; RewardDistributable internal rewardDistributor; // oraclize OraclizeLib.OraclizeData oraclizeData; // events event TicketPurchased(address indexed ticketPurchaser, uint indexed id, uint numTickets, uint totalCost, uint block); event WinnerSelected(address indexed winner, uint indexed id, uint winnings, uint block); event RandomProofFailed(bytes32 queryId, uint indexed id, uint block); function Raffle(uint _ticketPrice, address _rewardDistributor) public { ticketPrice = _ticketPrice; raffleState = RaffleState.Active; callbackGas = 200000; randomBytes = 8; fee = 5 finney; rewardDistributor = RewardDistributable(_rewardDistributor); oraclizeData.initializeOraclize(); randomSource = RandomSource.Qrng; resetRaffle(); } /// @dev Returns whether the game is active. function isActive() public constant returns (bool) { return raffleState == RaffleState.Active || raffleState == RaffleState.PendingInActive; } /// @dev Fallback function to purchase a single ticket. function () public payable { } /// @dev Gets the projected jackpot. /// @return The projected jackpot amount. function getProjectedJackpot() public constant returns (uint) { uint jackpot = getAbsoluteProjectedJackpot(); Jackpot memory totals = getJackpotTotals(jackpot); return totals.winnerTotal; } /// @dev Gets the actual jackpot /// @return The actual jackpot amount. function getJackpot() public constant returns (uint) { uint jackpot = getAbsoluteJackpot(); Jackpot memory totals = getJackpotTotals(jackpot); return totals.winnerTotal; } /// @dev Gets the ticket holder count /// @return The total ticket holder count function getTicketHolderCount() public constant returns (uint) { return getTotalTickets(); } /// @dev Updates the ticket price. function updateTicketPrice(uint updatedPrice) public onlyOwner { require(raffleState == RaffleState.InActive); require(updatedPrice > 0); ticketPrice = updatedPrice; } /// @dev Updates the ticket price. function updateFee(uint updatedFee) public onlyOwner { require(updatedFee > 0); fee = updatedFee; } /// @dev Deactivates the raffle after the next game. function deactivate() public onlyOwner { require(raffleState == RaffleState.Active); raffleState = ticketHolders.length == 0 ? RaffleState.InActive : RaffleState.PendingInActive; } /// @dev Activates the raffle, if inactivated. function activate() public onlyOwner { require(raffleState == RaffleState.InActive); raffleState = RaffleState.Active; } /// The oraclize callback function. function __callback(bytes32 queryId, string result, bytes proof) public { require(msg.sender == oraclizeData.oraclize_cbAddress()); // We only expect this for this callback if (oraclizeData.oraclize_randomDS_proofVerify__returnCode(queryId, result, proof) != 0) { RandomProofFailed(queryId, gameId, now); randomQueried = 0; return; } __callback(queryId, result); } /// The oraclize callback function. function __callback(bytes32 queryId, string result) public { require(msg.sender == oraclizeData.oraclize_cbAddress()); // Guard against the case where oraclize is triggered, or calls back multiple times. if (!shouldChooseWinner()) { return; } uint maxRange = 2**(8*randomBytes); uint randomNumber = uint(keccak256(result)) % maxRange; winnerSelected(randomNumber); } /// @dev An administrative function to allow in case the proof fails or /// a random winner needs to be chosen again. function forceChooseRandomWinner() public onlyOwner { require(raffleState != RaffleState.InActive); executeRandomQuery(); } /// @dev Forces a refund for all participants and deactivates the contract /// This offers a full refund, so it will be up to the owner to ensure a full balance. function forceRefund() public onlyOwner { raffleState = RaffleState.PendingInActive; uint total = getTotalTickets() * ticketPrice; require(this.balance > total); for (uint i = 0; i < ticketHolders.length; i++) { TicketHolder storage holder = ticketHolders[i]; holder.purchaser.transfer(uint256(holder.count).mul(ticketPrice)); } resetRaffle(); } /// @dev Destroys the current contract and moves all ETH back to function updateRewardDistributor(address newRewardDistributor) public onlyOwner { rewardDistributor = RewardDistributable(newRewardDistributor); } /// @dev Destroys the current contract and moves all ETH back to /// owner. Only can occur after state has been set to inactive. function destroy() public onlyOwner { require(raffleState == RaffleState.InActive); selfdestruct(owner); } /// Gets the projected jackpot prior to any fees /// @return The projected jackpot prior to any fees function getAbsoluteProjectedJackpot() internal constant returns (uint); /// Gets the actual jackpot prior to any fees /// @return The actual jackpot amount prior to any fees. function getAbsoluteJackpot() internal constant returns (uint); /// An abstract function which determines whether a it is appropriate to choose a winner. /// @return True if it is appropriate to choose the winner, false otherwise. function shouldChooseWinner() internal returns (bool); function executeRandomQuery() internal { if (randomSource == RandomSource.RandomDS) { oraclizeData.oraclize_newRandomDSQuery(0, randomBytes, callbackGas); } else { oraclizeData.oraclize_query("URL","json(https://qrng.anu.edu.au/API/jsonI.php?length=1&type=hex16&size=32).data[0]", callbackGas); } } /// Chooses the winner at random. function chooseWinner() internal { // We build in a buffer of 20 blocks. Approx 1 block per 15 secs ~ 5 mins // the last time random was queried, we'll execute again. if (randomQueried < (block.number.sub(20))) { executeRandomQuery(); randomQueried = block.number; } } /// Internal function for when a winner is chosen. function winnerSelected(uint randomNumber) internal { TicketHolder memory winner = getWinningTicketHolder(randomNumber); uint jackpot = getAbsoluteJackpot(); Jackpot memory jackpotTotals = getJackpotTotals(jackpot); WinnerSelected(winner.purchaser, gameId, jackpotTotals.winnerTotal, now); transferJackpot(winner.purchaser, jackpotTotals.winnerTotal); transferCascades(jackpotTotals.absoluteTotal); resetRaffle(); } function getWinningTicketHolder(uint randomNumber) internal view returns(TicketHolder) { assert(ticketHolders.length > 0); uint totalTickets = getTotalTickets(); uint winner = (randomNumber % totalTickets) + 1; uint min = 0; uint max = ticketHolders.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (ticketHolders[mid].runningTotal >= winner && (ticketHolders[mid].runningTotal-ticketHolders[mid].count) < winner) { return ticketHolders[mid]; } if (ticketHolders[mid].runningTotal <= winner) { min = mid; } else { max = mid-1; } } return ticketHolders[min]; } /// Transfers the jackpot to the winner triggering the event function transferJackpot(address winner, uint jackpot) internal returns(uint) { // We explicitly do not use transfer here because if the // the call fails, the oraclize contract will not retry. bool sendSuccessful = winner.send(jackpot); if (!sendSuccessful) { addPendingWinner(winner, jackpot); } return jackpot; } /// Resets the raffle game state. function resetRaffle() internal { if (raffleState == RaffleState.PendingInActive) { raffleState = RaffleState.InActive; } ticketHolders.length = 0; gameId = block.number; randomQueried = 0; } /// Gets the jackpot after fees function getJackpotTotals(uint jackpot) internal constant returns(Jackpot) { if (jackpot < fee) { return Jackpot(0, 0, 0, 0); } uint cascadeTotal = getCascadeTotal(totalCascadingPercentage, jackpot); return Jackpot(jackpot, fee, cascadeTotal, jackpot.sub(fee).sub(cascadeTotal)); } function updateRandomSource(uint newRandomSource) public onlyOwner { if (newRandomSource == 1) { randomSource = RandomSource.RandomDS; } else { randomSource = RandomSource.Qrng; } setProof(); } function setProof() internal { if (randomSource == RandomSource.RandomDS) { // proofType_Ledger = 0x30; oraclizeData.oraclize_setProof(0x30); } else { oraclizeData.oraclize_setProof(0x00); } } function getTotalTickets() internal view returns(uint) { return ticketHolders.length == 0 ? 0 : ticketHolders[ticketHolders.length-1].runningTotal; } function updateOraclizeGas(uint newCallbackGas, uint customGasPrice) public onlyOwner { callbackGas = newCallbackGas; updateCustomGasPrice(customGasPrice); } function updateCustomGasPrice(uint customGasPrice) internal { oraclizeData.oraclize_setCustomGasPrice(customGasPrice); } } contract CountBasedRaffle is Raffle { uint public drawTicketCount; /// @dev Constructor for conventional raffle /// @param _ticketPrice The ticket price. /// @param _drawTicketCount The number of tickets for a draw to take place. function CountBasedRaffle(uint _ticketPrice, uint _drawTicketCount, address _rewardDistributor) Raffle(_ticketPrice, _rewardDistributor) public { drawTicketCount = _drawTicketCount; } /// @dev Gets the projected jackpot. function getAbsoluteProjectedJackpot() internal constant returns (uint) { uint totalTicketCount = getTotalTickets(); uint ticketCount = drawTicketCount > totalTicketCount ? drawTicketCount : totalTicketCount; return ticketCount.mul(ticketPrice); } /// @dev Gets the actual jackpot function getAbsoluteJackpot() internal constant returns (uint) { if (ticketHolders.length == 0) { return 0; } return this.balance.sub(totalPendingPayments); } /* @dev Purchases tickets to the raffle. * @param numTickets Number of tickets to purchase. * @param referrer The address of the referrer. */ function purchaseTicket(uint numTickets, address referrer) public payable costsExactly(numTickets.mul(ticketPrice)) { require(raffleState != RaffleState.InActive); require(numTickets < drawTicketCount); // Add the address to the ticketHolders. uint totalTickets = getTotalTickets(); ticketHolders.push(TicketHolder(msg.sender, uint16(numTickets), uint80(totalTickets.add(numTickets)))); TicketPurchased(msg.sender, gameId, numTickets, ticketPrice.mul(numTickets), now); if (rewardDistributor != address(0)) { rewardDistributor.registerReferral(msg.sender, referrer); rewardDistributor.transferRewards(msg.sender, msg.value, gameId); } if (shouldChooseWinner()) { chooseWinner(); } } /// An abstract function which determines whether a it is appropriate to choose a winner. /// @return True if it is appropriate to choose the winner, false otherwise. function shouldChooseWinner() internal returns (bool) { return getTotalTickets() >= drawTicketCount; } } contract GoldRaffle is CountBasedRaffle { /// @dev Constructor for conventional raffle /// Should reach jackpot of ~ 1.5 ETH function GoldRaffle(address _rewardDistributor) CountBasedRaffle(100 finney, 10, _rewardDistributor) public { } } contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) public payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) public payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) public payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) public; function setConfig(bytes32 _config) public; function setCustomGasPrice(uint _gasPrice) public; function randomDS_getSessionPubKeyHash() public returns(bytes32); }
records the winner so that a transfer or withdraw can occur at a later date.
function addPendingWinner(address winner, uint amount) internal { pendingPayments[winner] = pendingPayments[winner].add(amount); totalPendingPayments = totalPendingPayments.add(amount); pendingWinners.push(winner); }
12,742,277
// SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: Matt W - NFT.sol // André Luque pragma solidity >=0.8.2; // to enable certain compiler features //import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), '.json')) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } contract nft is ERC721, Ownable { //baseURI that is established string private _currentBaseURI; //accumulate the number of tokens that have been minted uint256 public numberOfTokens; //limit the tokens that can be minted uint256 public maxTokens; //stores the amount of mints each address has had mapping(address => uint) private mintsPerAddress; //price to pay for each nft uint256 private mintCost_ = 0.03 ether; //stores value of current reserved NFTs minted by creator uint private reservedMints; //stores the maimum amount of reserved mints allowed uint private maxReservedMints; constructor() ERC721('Reaper Boys', 'REAP') { //this uri will only be used once revealed is on _currentBaseURI = 'ipfs://Qme9M4eaLxRzMXp5k3rHuTSAxBCUTBBStyft7PLExayGAr/'; //start off with zero tokens and max in total collection will be 10k numberOfTokens = 0; maxTokens = 9999; //reserved mints values reservedMints = 0; maxReservedMints = 100; //minting the team´s NFTs _safeMint(msg.sender, 990); _safeMint(msg.sender, 3595); _safeMint(msg.sender, 8549); mintsPerAddress[msg.sender] += 3; numberOfTokens += 3; reservedMints += 3; } //this uri will only be used once revealed is on function setBaseURI(string memory baseURI) public onlyOwner { _currentBaseURI = baseURI; } //function to see the current baseURI function _baseURI() internal view override returns (string memory) { return _currentBaseURI; } //tokens are numbered from 1 to 10 function tokenId() internal view returns(uint256) { uint currentId = numberOfTokens - reservedMints; bool exists = true; while (exists || currentId == 6138) { currentId += 1; exists = _exists(currentId); } return currentId; } //minting a new NFT function mint(uint number) payable public { require(numberOfTokens + number <= maxTokens - (maxReservedMints - reservedMints), 'Max Number of Tokens reached!'); require(msg.value >= mintCost_ * number, 'insufficient Funds, Price of each NFT is 0.03'); for (uint256 i = 0; i < number; i++) { uint256 tid = tokenId(); _safeMint(msg.sender, tid); mintsPerAddress[msg.sender] += 1; numberOfTokens += 1; } //get amount of eth sent to pay for minting and automatically send to owner sendToOwner(); } //reserved NFTs for creator function reservedMintCreator(uint256 number) public onlyOwner { require(reservedMints + number <= maxReservedMints, "Not enough Reserved NFTs left to mint.."); for (uint256 i = 0; i < number; i++) { uint tid = tokenId(); _safeMint(msg.sender, tid); mintsPerAddress[msg.sender] += 1; numberOfTokens += 1; reservedMints += 1; } } //sending mint fees to owner function sendToOwner() internal { address payable owner_ = payable(owner()); (bool success, ) = owner_.call{value: msg.value}(""); require(success, "Address: unable to send value, recipient may have reverted"); } //function for the owner to see how many reserved mints he has left function reservedMintsLeft() public onlyOwner view returns(uint) { return maxReservedMints - reservedMints; } //total amount of NFTs that have been minted function totalSupply() public view returns(uint) { return numberOfTokens; } }
function to see the current baseURI
function _baseURI() internal view override returns (string memory) { return _currentBaseURI; }
270,851
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "../src/interfaces/IStructs.sol"; import "./TestStakingNoWETH.sol"; contract TestProtocolFees is TestStakingNoWETH { struct TestPool { uint96 operatorStake; uint96 membersStake; mapping(address => bool) isMaker; } event ERC20ProxyTransferFrom( address from, address to, uint256 amount ); mapping(bytes32 => TestPool) private _testPools; mapping(address => bytes32) private _makersToTestPoolIds; constructor(address exchangeAddress) public { _addAuthorizedAddress(msg.sender); init(); validExchanges[exchangeAddress] = true; _removeAuthorizedAddressAtIndex(msg.sender, 0); } function advanceEpoch() external { currentEpoch += 1; } /// @dev Create a test pool. function createTestPool( bytes32 poolId, uint96 operatorStake, uint96 membersStake, address[] calldata makerAddresses ) external { TestPool storage pool = _testPools[poolId]; pool.operatorStake = operatorStake; pool.membersStake = membersStake; for (uint256 i = 0; i < makerAddresses.length; ++i) { pool.isMaker[makerAddresses[i]] = true; _makersToTestPoolIds[makerAddresses[i]] = poolId; poolIdByMaker[makerAddresses[i]] = poolId; } } /// @dev The ERC20Proxy `transferFrom()` function. function transferFrom( address from, address to, uint256 amount ) external returns (bool) { emit ERC20ProxyTransferFrom(from, to, amount); return true; } function getAggregatedStatsForCurrentEpoch() external view returns (IStructs.AggregatedStats memory) { return aggregatedStatsByEpoch[currentEpoch]; } /// @dev Overridden to use test pools. function getStakingPoolIdOfMaker(address makerAddress) public view returns (bytes32) { return _makersToTestPoolIds[makerAddress]; } /// @dev Overridden to use test pools. function getTotalStakeDelegatedToPool(bytes32 poolId) public view returns (IStructs.StoredBalance memory balance) { TestPool memory pool = _testPools[poolId]; uint96 stake = pool.operatorStake + pool.membersStake; return IStructs.StoredBalance({ currentEpoch: currentEpoch.downcastToUint64(), currentEpochBalance: stake, nextEpochBalance: stake }); } /// @dev Overridden to use test pools. function getStakeDelegatedToPoolByOwner(address, bytes32 poolId) public view returns (IStructs.StoredBalance memory balance) { TestPool memory pool = _testPools[poolId]; return IStructs.StoredBalance({ currentEpoch: currentEpoch.downcastToUint64(), currentEpochBalance: pool.operatorStake, nextEpochBalance: pool.operatorStake }); } function getWethContract() public view returns (IEtherToken wethContract) { return IEtherToken(address(this)); } }
Overridden to use test pools.
function getStakeDelegatedToPoolByOwner(address, bytes32 poolId) public view returns (IStructs.StoredBalance memory balance) { TestPool memory pool = _testPools[poolId]; return IStructs.StoredBalance({ currentEpoch: currentEpoch.downcastToUint64(), currentEpochBalance: pool.operatorStake, nextEpochBalance: pool.operatorStake }); }
1,783,285
pragma solidity >=0.5.7 <0.6.0; /* * xEuro.sol * xEUR tokens smart contract * implements [ERC-20 Token Standard](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) * ver. 1.0.0 * 2019-04-15 * https://xeuro.online * https://etherscan.io/address/0xC31C61cf55fB5E646684AD8E8517793ec9A22c5e * deployed on block: 7571826 * solc version : 0.5.7+commit.6da8b019 **/ /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /* "Interfaces" */ // see: https://github.com/ethereum/EIPs/issues/677 contract tokenRecipient { function tokenFallback(address _from, uint256 _value, bytes memory _extraData) public returns (bool); } contract xEuro { // see: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol using SafeMath for uint256; /* --- ERC-20 variables ----- */ // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#name // function name() constant returns (string name) string public name = "xEuro"; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#symbol // function symbol() constant returns (string symbol) string public symbol = "xEUR"; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#decimals // function decimals() constant returns (uint8 decimals) uint8 public decimals = 0; // 1 token = €1, no smaller unit // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#totalsupply // function totalSupply() constant returns (uint256 totalSupply) // we start with zero uint256 public totalSupply = 0; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#balanceof // function balanceOf(address _owner) constant returns (uint256 balance) mapping(address => uint256) public balanceOf; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#allowance // function allowance(address _owner, address _spender) constant returns (uint256 remaining) mapping(address => mapping(address => uint256)) public allowance; /* --- administrative variables */ // admins mapping(address => bool) public isAdmin; // addresses allowed to mint tokens: mapping(address => bool) public canMint; // addresses allowed to transfer tokens from contract's own address: mapping(address => bool) public canTransferFromContract; // addresses allowed to burn tokens (on contract's own address): mapping(address => bool) public canBurn; /* ---------- Constructor */ // do not forget about: // https://medium.com/@codetractio/a-look-into-paritys-multisig-wallet-bug-affecting-100-million-in-ether-and-tokens-356f5ba6e90a constructor() public {// Constructor must be public or internal isAdmin[msg.sender] = true; canMint[msg.sender] = true; canTransferFromContract[msg.sender] = true; canBurn[msg.sender] = true; } /* --- ERC-20 events */ // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#events // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer-1 event Transfer(address indexed from, address indexed to, uint256 value); /* --- Interaction with other contracts events */ event DataSentToAnotherContract(address indexed _from, address indexed _toContract, bytes _extraData); /* --- ERC-20 Functions */ // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#methods // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer function transfer(address _to, uint256 _value) public returns (bool){ return transferFrom(msg.sender, _to, _value); } // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transferfrom function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ // Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event (ERC-20) require(_value >= 0); // The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism require(msg.sender == _from || _value <= allowance[_from][msg.sender] || (_from == address(this) && canTransferFromContract[msg.sender])); // check if _from account have required amount require(_value <= balanceOf[_from]); if (_to == address(this)) { // (!) only token holder can send tokens to smart contract to get fiat, not using allowance require(_from == msg.sender); } balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); // If allowance used, change allowances correspondingly if (_from != msg.sender && _from != address(this)) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); } if (_to == address(this) && _value > 0) { require(_value >= minExchangeAmount); tokensInEventsCounter++; tokensInTransfer[tokensInEventsCounter].from = _from; tokensInTransfer[tokensInEventsCounter].value = _value; tokensInTransfer[tokensInEventsCounter].receivedOn = now; emit TokensIn( _from, _value, tokensInEventsCounter ); } emit Transfer(_from, _to, _value); return true; } /* ---------- Interaction with other contracts */ /* https://github.com/ethereum/EIPs/issues/677 * transfer tokens with additional info to another smart contract, and calls its correspondent function * @param address _to - another smart contract address * @param uint256 _value - number of tokens * @param bytes _extraData - data to send to another contract * > this may be used to convert pre-ICO tokens to ICO tokens */ function transferAndCall(address _to, uint256 _value, bytes memory _extraData) public returns (bool){ tokenRecipient receiver = tokenRecipient(_to); if (transferFrom(msg.sender, _to, _value)) { if (receiver.tokenFallback(msg.sender, _value, _extraData)) { emit DataSentToAnotherContract(msg.sender, _to, _extraData); return true; } } return false; } // the same as above, but for all tokens on user account // for example for converting ALL tokens of user account to another tokens function transferAllAndCall(address _to, bytes memory _extraData) public returns (bool){ return transferAndCall(_to, balanceOf[msg.sender], _extraData); } /* --- Administrative functions */ /* --- isAdmin */ event AdminAdded(address indexed by, address indexed newAdmin);// function addAdmin(address _newAdmin) public returns (bool){ require(isAdmin[msg.sender]); isAdmin[_newAdmin] = true; emit AdminAdded(msg.sender, _newAdmin); return true; } // event AdminRemoved(address indexed by, address indexed _oldAdmin);// function removeAdmin(address _oldAdmin) public returns (bool){ require(isAdmin[msg.sender]); // prevents from deleting the last admin (can be multisig smart contract) by itself: require(msg.sender != _oldAdmin); isAdmin[_oldAdmin] = false; emit AdminRemoved(msg.sender, _oldAdmin); return true; } uint256 minExchangeAmount = 12; // xEuro tokens event minExchangeAmountChanged (address indexed by, uint256 from, uint256 to); // function changeMinExchangeAmount(uint256 _minExchangeAmount) public returns (bool){ require(isAdmin[msg.sender]); uint256 from = minExchangeAmount; minExchangeAmount = _minExchangeAmount; emit minExchangeAmountChanged(msg.sender, from, minExchangeAmount); return true; } /* --- canMint */ event AddressAddedToCanMint(address indexed by, address indexed newAddress); // function addToCanMint(address _newAddress) public returns (bool){ require(isAdmin[msg.sender]); canMint[_newAddress] = true; emit AddressAddedToCanMint(msg.sender, _newAddress); return true; }// event AddressRemovedFromCanMint(address indexed by, address indexed removedAddress);// function removeFromCanMint(address _addressToRemove) public returns (bool){ require(isAdmin[msg.sender]); canMint[_addressToRemove] = false; emit AddressRemovedFromCanMint(msg.sender, _addressToRemove); return true; } /* --- canTransferFromContract*/ event AddressAddedToCanTransferFromContract(address indexed by, address indexed newAddress); // function addToCanTransferFromContract(address _newAddress) public returns (bool){ require(isAdmin[msg.sender]); canTransferFromContract[_newAddress] = true; emit AddressAddedToCanTransferFromContract(msg.sender, _newAddress); return true; }// event AddressRemovedFromCanTransferFromContract(address indexed by, address indexed removedAddress);// function removeFromCanTransferFromContract(address _addressToRemove) public returns (bool){ require(isAdmin[msg.sender]); canTransferFromContract[_addressToRemove] = false; emit AddressRemovedFromCanTransferFromContract(msg.sender, _addressToRemove); return true; } /* --- canBurn */ event AddressAddedToCanBurn(address indexed by, address indexed newAddress); // function addToCanBurn(address _newAddress) public returns (bool){ require(isAdmin[msg.sender]); canBurn[_newAddress] = true; emit AddressAddedToCanBurn(msg.sender, _newAddress); return true; }// event AddressRemovedFromCanBurn(address indexed by, address indexed removedAddress);// function removeFromCanBurn(address _addressToRemove) public returns (bool){ require(isAdmin[msg.sender]); canBurn[_addressToRemove] = false; emit AddressRemovedFromCanBurn(msg.sender, _addressToRemove); return true; } /* ---------- Create and burn tokens */ /* -- Accounting: exchange fiat to tokens (fiat sent to our bank acc with eth acc in reference > tokens ) */ uint public mintTokensEventsCounter = 0;// struct MintTokensEvent { address mintedBy; // uint256 fiatInPaymentId; uint value; // uint on; // UnixTime uint currentTotalSupply; } // // keep all fiat tx ids, to prevent minting tokens twice (or more times) for the same fiat tx mapping(uint256 => bool) public fiatInPaymentIds; // here we can find a MintTokensEvent by fiatInPaymentId, // so we now if tokens were minted for given incoming fiat payment mapping(uint256 => MintTokensEvent) public fiatInPaymentsToMintTokensEvent; // here we store MintTokensEvent with its ordinal numbers mapping(uint256 => MintTokensEvent) public mintTokensEvent; // event TokensMinted( address indexed by, uint256 indexed fiatInPaymentId, uint value, uint currentTotalSupply, uint indexed mintTokensEventsCounter ); // tokens should be minted to contracts own address, (!) after that tokens should be transferred using transferFrom function mintTokens(uint256 value, uint256 fiatInPaymentId) public returns (bool){ require(canMint[msg.sender]); // require that this fiatInPaymentId was not used before: require(!fiatInPaymentIds[fiatInPaymentId]); require(value >= 0); // <<< this is the moment when new tokens appear in the system totalSupply = totalSupply.add(value); // first token holder of fresh minted tokens is the contract itself balanceOf[address(this)] = balanceOf[address(this)].add(value); mintTokensEventsCounter++; mintTokensEvent[mintTokensEventsCounter].mintedBy = msg.sender; mintTokensEvent[mintTokensEventsCounter].fiatInPaymentId = fiatInPaymentId; mintTokensEvent[mintTokensEventsCounter].value = value; mintTokensEvent[mintTokensEventsCounter].on = block.timestamp; mintTokensEvent[mintTokensEventsCounter].currentTotalSupply = totalSupply; // fiatInPaymentsToMintTokensEvent[fiatInPaymentId] = mintTokensEvent[mintTokensEventsCounter]; emit TokensMinted(msg.sender, fiatInPaymentId, value, totalSupply, mintTokensEventsCounter); fiatInPaymentIds[fiatInPaymentId] = true; return true; } // requires msg.sender be both 'canMint' and 'canTransferFromContract' function mintAndTransfer( uint256 _value, uint256 fiatInPaymentId, address _to ) public returns (bool){ if (mintTokens(_value, fiatInPaymentId) && transferFrom(address(this), _to, _value)) { return true; } return false; } /* -- Accounting: exchange tokens to fiat (tokens sent to contract owns address > fiat payment) */ uint public tokensInEventsCounter = 0;// struct TokensInTransfer {// <<< used in 'transfer' address from; // uint value; // uint receivedOn; // UnixTime } // mapping(uint256 => TokensInTransfer) public tokensInTransfer; // event TokensIn( address indexed from, uint256 value, uint256 indexed tokensInEventsCounter );// uint public burnTokensEventsCounter = 0;// struct burnTokensEvent { address by; // uint256 value; // uint256 tokensInEventId; uint256 fiatOutPaymentId; uint256 burnedOn; // UnixTime uint256 currentTotalSupply; } // mapping(uint => burnTokensEvent) public burnTokensEvents; // we count every fiat payment id used when burn tokens to prevent using it twice mapping(uint256 => bool) public fiatOutPaymentIdsUsed; // event TokensBurned( address indexed by, uint256 value, uint256 indexed tokensInEventId, uint256 indexed fiatOutPaymentId, uint burnedOn, // UnixTime uint currentTotalSupply ); // (!) only contract's own tokens (balanceOf[this]) can be burned function burnTokens( uint256 value, uint256 tokensInEventId, uint256 fiatOutPaymentId ) public returns (bool){ require(canBurn[msg.sender]); require(value >= 0); require(balanceOf[address(this)] >= value); // require(!tokensInEventIdsUsed[tokensInEventId]); require(!fiatOutPaymentIdsUsed[fiatOutPaymentId]); balanceOf[address(this)] = balanceOf[address(this)].sub(value); totalSupply = totalSupply.sub(value); burnTokensEventsCounter++; burnTokensEvents[burnTokensEventsCounter].by = msg.sender; burnTokensEvents[burnTokensEventsCounter].value = value; burnTokensEvents[burnTokensEventsCounter].tokensInEventId = tokensInEventId; burnTokensEvents[burnTokensEventsCounter].fiatOutPaymentId = fiatOutPaymentId; burnTokensEvents[burnTokensEventsCounter].burnedOn = block.timestamp; burnTokensEvents[burnTokensEventsCounter].currentTotalSupply = totalSupply; emit TokensBurned(msg.sender, value, tokensInEventId, fiatOutPaymentId, block.timestamp, totalSupply); fiatOutPaymentIdsUsed[fiatOutPaymentId]; return true; } }
the same as above, but for all tokens on user account for example for converting ALL tokens of user account to another tokens
function transferAllAndCall(address _to, bytes memory _extraData) public returns (bool){ return transferAndCall(_to, balanceOf[msg.sender], _extraData); }
5,492,564
./partial_match/8453/0x22DD6e844225f1966Bf9D956C7Fe03fb198171eF/sources/ERC20.sol
https:github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/IERC20.sol
interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom( address sender, address recipient, uint amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); pragma solidity ^0.8.19; }
16,696,500
pragma solidity ^0.8.6; contract DIONS_SC_FAUCET { function deposit(uint256 d) public payable { require(msg.value == d); d = msg.value; } function getContractBalance() public view returns (uint256) { return address(this).balance; } function withdraw() public { //msg.sender.transfer(address(this).balance); payable(msg.sender).transfer(address(this).balance); } receive() external payable { } }
msg.sender.transfer(address(this).balance);
function withdraw() public { payable(msg.sender).transfer(address(this).balance); }
12,673,244
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.2; // import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; // import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev 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; } } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll( address indexed account, address indexed operator, bool approved ); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:ERC1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:ERC1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); /** * @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 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); } } } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; struct Metadata { string name; string ipfsimage; string ipfsmetadata; } // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) public _balances; mapping(uint256 => Metadata) token_id; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; mapping(uint256 => address) public _creator; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_,string memory name_, string memory symbol_) { _setURI(uri_); _name = name_; _symbol = symbol_; } /** * @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 {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 tokenId) public view virtual override returns (string memory ipfsmetadata) { // return _uri; Metadata memory date = token_id[tokenId]; ipfsmetadata = date.ipfsmetadata; // string memory ipfsmetadata = getmetadata(tokenId); return ipfsmetadata; } /** * @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); } function _setApprovalForAll(address owner,address operator, bool approved) internal { _operatorApprovals[owner][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, address(this)), "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 IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver.onERC1155BatchReceived.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. 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); } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155, Ownable { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, address(this)) || owner() == _msgSender(), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, address(this)), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } 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 Woonkly { // function setApproved(address operator, bool approved) external returns (uint256); // } interface 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); } contract AidiCraftMultiple is ERC1155, Ownable, ERC1155Burnable{ event Approve( address indexed owner, uint256 indexed token_id, bool approved ); event OrderPlace( address indexed from, uint256 indexed tokenId, uint256 indexed value ); event CancelOrder(address indexed from, uint256 indexed tokenId); event ChangePrice(address indexed from, uint256 indexed tokenId, uint256 indexed value); using SafeMath for uint256; struct Order { uint256 tokenId; uint256 price; } mapping(address => mapping(uint256 => Order)) public order_place; mapping(uint256 => mapping(address => bool)) public checkOrder; mapping(uint256 => uint256) public totalQuantity; mapping(uint256 => uint256) public _royal; mapping(string => address) private tokentype; uint256 private serviceValue; string private _currentBaseURI; uint256 public _tid; struct tokenfee { address tokenAddress; uint256 tokenfee; } mapping(string => tokenfee) public Tokendetail; constructor( uint256 id, uint256 _serviceValue, string memory _name, string memory _symbol ) ERC1155("",_name,_symbol) { _tid = id; serviceValue = _serviceValue; addTokenType("WETH",0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2,2500000000000000000); addTokenType("VERSE",0xe18841d7A75866688E291703BdE66c3378bd74A3,2000000000000000000); } function getServiceFee() public view returns (uint256) { return serviceValue; } function serviceFunction(uint256 _serviceValue) public onlyOwner{ serviceValue = _serviceValue; } function addID(uint256 value) public returns (uint256) { _tid = _tid + value; return _tid; } function getTokenAddress(string memory _type) public view returns (address) { return tokentype[_type]; } function addTokenType(string memory _type, address tokenAddress, uint256 fee) public onlyOwner { tokenfee memory tokenfees; tokenfees.tokenAddress = tokenAddress; tokenfees.tokenfee = fee; Tokendetail[_type] = tokenfees; } function getTokenFee(string memory _type)public view returns(uint256){ return Tokendetail[_type].tokenfee; } function EditTokenType (string memory _type,uint256 fee)public onlyOwner{ Tokendetail[_type].tokenfee=fee; } function DeleteTokenType (string memory _type) public onlyOwner{ delete Tokendetail[_type]; } function setApproval(address operator, bool approved) public returns (uint256) { setApprovalForAll(operator, approved); uint256 id_ = addID(1).add(block.timestamp); emit Approve(msg.sender, id_, approved); return id_; } function mint(uint256 id, uint256 value, uint256 royal, uint256 nooftoken, string memory ipfsname, string memory ipfsimage, string memory ipfsmetadata ) public { _mint(msg.sender, id, nooftoken, ""); token_id[id] = Metadata(ipfsname, ipfsimage, ipfsmetadata); _creator[id]=msg.sender; _royal[id]=royal; if(value != 0){ orderPlace(id, value); } } function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts ) public { _mintBatch(to, ids, amounts, ""); } function saleWithToken( address payable from, uint256 tokenId, uint256 amount, uint256 nooftoken, string memory bidtoken ) public{ require(amount == order_place[from][tokenId].price.mul(nooftoken) , "Insufficent Balance"); _saleToken(from, tokenId, amount, bidtoken); _setApprovalForAll(from, msg.sender,true); saleTokenTransfer(from, tokenId, nooftoken); } function saleToken( address payable from, uint256 tokenId, uint256 amount, uint256 nooftoken ) public payable { require(amount == order_place[from][tokenId].price.mul(nooftoken) , "Invalid Balance"); _saleToken(from, tokenId, amount, "BNB"); _setApprovalForAll(from, msg.sender,true); saleTokenTransfer(from, tokenId, nooftoken); } function _saleToken( address payable from, uint256 tokenId, uint256 amount, string memory bidtoken ) internal { if(keccak256(abi.encodePacked((bidtoken))) == keccak256(abi.encodePacked(("ETH")))){ uint256 val = pERCent(amount, serviceValue).add(amount); require( msg.value == val, "Insufficient Balance"); address payable create = payable(_creator[tokenId]); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue); require( msg.value == _adminfee.add(roy.add(netamount)), "Insufficient Balance"); address payable admin = payable(owner()); admin.transfer(_adminfee); create.transfer(roy); from.transfer(netamount); } else{ uint256 dyntokfee = Tokendetail[bidtoken].tokenfee; uint256 val = pERCent(amount, dyntokfee).add(amount); ERC20 t = ERC20(Tokendetail[bidtoken].tokenAddress); uint256 approveValue = t.allowance(msg.sender, address(this)); require( approveValue >= val, "Approve Value Mismatches"); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], dyntokfee); require( approveValue >= _adminfee.add(roy.add(netamount)), "Value difference in the Admin Fee"); t.transferFrom(msg.sender, owner(), _adminfee); t.transferFrom(msg.sender,_creator[tokenId],roy); t.transferFrom(msg.sender,from,netamount); } } function pERCent(uint256 value1, uint256 value2) internal pure returns (uint256) { uint256 result = value1.mul(value2).div(1e20); return (result); } function calc( uint256 amount, uint256 royal, uint256 _serviceValue ) internal pure returns ( uint256, uint256, uint256 ) { uint256 fee = pERCent(amount, _serviceValue); uint256 roy = pERCent(amount, royal); uint256 netamount = amount.sub(fee.add(roy)); fee = fee.add(fee); return (fee, roy, netamount); } function saleTokenTransfer( address payable from, uint256 tokenId, uint256 NOFToken ) internal { safeTransferFrom(from, msg.sender, tokenId, NOFToken, ""); } function acceptBId(string memory bidtoken,address bidaddr, uint256 amount, uint256 tokenId, uint256 NOFToken) public{ _acceptBId(bidtoken, bidaddr, amount, tokenId, owner()); tokenTrans(tokenId, msg.sender, bidaddr, NOFToken); if(checkOrder[tokenId][msg.sender] == true){ if(_balances[tokenId][msg.sender] == 0){ delete order_place[msg.sender][tokenId]; checkOrder[tokenId][msg.sender] = false; } } } function _acceptBId(string memory tokenAss,address from, uint256 amount, uint256 tokenId, address admin) internal{ uint256 dyntokfee = Tokendetail[tokenAss].tokenfee; uint256 val = pERCent(amount, dyntokfee).add(amount); ERC20 t = ERC20(Tokendetail[tokenAss].tokenAddress); uint256 approveValue = t.allowance(from, address(this)); require( approveValue >= val, "Insufficient Balance"); require(_balances[tokenId][msg.sender] > 0, "Is Not a Owner"); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], dyntokfee); require( approveValue >= _adminfee.add(roy.add(netamount)), "Insufficient Balance"); t.transferFrom(from, admin, _adminfee); t.transferFrom(from,_creator[tokenId],roy); t.transferFrom(from,msg.sender,netamount); } function tokenTrans(uint256 tokenId,address from, address to, uint256 NOFToken) internal{ safeTransferFrom(from,to, tokenId, NOFToken, ""); } function orderPlace(uint256 tokenId, uint256 _price) public{ require( _balances[tokenId][msg.sender] > 0, "Is Not a Owner"); Order memory order; order.tokenId = tokenId; order.price = _price; order_place[msg.sender][tokenId] = order; checkOrder[tokenId][msg.sender] = true; emit OrderPlace(msg.sender, tokenId, _price); } function cancelOrder(uint256 tokenId) public{ require(_balances[tokenId][msg.sender] > 0, "Is Not a Owner"); delete order_place[msg.sender][tokenId]; checkOrder[tokenId][msg.sender] = false; emit CancelOrder(msg.sender, tokenId); } function changePrice(uint256 value, uint256 tokenId) public{ require( _balances[tokenId][msg.sender] > 0, "Is Not a Owner"); require( value < order_place[msg.sender][tokenId].price); order_place[msg.sender][tokenId].price = value; emit ChangePrice(msg.sender, tokenId, value); } function burnToken(address from, uint256 tokenId, uint256 NOFToken ) public{ require( (_balances[tokenId][from] >= NOFToken && from == msg.sender) || msg.sender == owner(), "Your Not a Token Owner or insufficient Token Balance"); require( _balances[tokenId][from] >= NOFToken, "Your Not a Token Owner or insufficient Token Balance"); burn(from, tokenId, NOFToken); if(_balances[tokenId][from] == NOFToken){ if(checkOrder[tokenId][from]==true){ delete order_place[from][tokenId]; checkOrder[tokenId][from] = false; } } } }
See {IERC1155MetadataURI-uri}. This implementation returns the same URI for all token types. It relies on the token type ID substitution mechanism Clients calling this function must replace the `\{id\}` substring with the actual token type ID./ return _uri; string memory ipfsmetadata = getmetadata(tokenId);
function uri(uint256 tokenId) public view virtual override returns (string memory ipfsmetadata) { Metadata memory date = token_id[tokenId]; ipfsmetadata = date.ipfsmetadata; return ipfsmetadata; }
445,490
/** *Submitted for verification at Etherscan.io on 2021-09-13 */ /** *Submitted for verification at Etherscan.io on 2021-09-13 */ // Sources flattened with hardhat v2.6.4 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] pragma solidity ^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 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"); } } } // File @openzeppelin/contracts/proxy/[email protected] pragma solidity ^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 `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] 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; } } } // File contracts/ThrTokenTimelock.sol pragma solidity ^0.8.0; contract ThrTokenTimelock is Initializable { using SafeERC20 for IERC20; // ERC20 basic token contract being held IERC20 private _token; // beneficiary of tokens after they are released address private _beneficiary; // timestamp when token release is enabled uint256 private _releaseTime; function initialize( IERC20 token_, address beneficiary_, uint256 releaseTime_ ) external initializer { require(releaseTime_ > block.timestamp, "TokenTimelock: release time is before current time"); _token = token_; _beneficiary = beneficiary_; _releaseTime = releaseTime_; } /** * @return the token being held. */ function token() public view virtual returns (IERC20) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view virtual returns (address) { return _beneficiary; } /** * @return the time when the tokens are released. */ function releaseTime() public view virtual returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public virtual { require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); uint256 amount = token().balanceOf(address(this)); require(amount > 0, "TokenTimelock: no tokens to release"); token().safeTransfer(beneficiary(), amount); } } // File contracts/ThrTimelockFactoryClone.sol pragma solidity 0.8.7; contract ThrTimelockFactoryClone { address immutable tokenTimeLockImplementation; event NewTimeLockContract(address indexed tokenTimeLockAddress); constructor() { tokenTimeLockImplementation = address(new ThrTokenTimelock()); } function createTokenTimelock(IERC20 token_, address beneficiary_, uint256 releaseTime_) external returns (address) { address clone = Clones.clone(tokenTimeLockImplementation); ThrTokenTimelock(clone).initialize(token_, beneficiary_, releaseTime_); emit NewTimeLockContract(clone); return clone; } }
Interface of the ERC20 standard as defined in the EIP./
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); }
150,054
./partial_match/42/0x87fb3EeDaD63411242145dA215fFF0099A1A4432/sources/BController.sol
hypothetical account shortfall below collateral requirements)/ Get the rating value from the BirdOracle for the account For each asset the account is in Read the balances and exchange rate from the bToken Calculate effects of interacting with bTokenModify redeem effect sumBorrowPlusEffects += tokensToDenom redeemTokens
function getHypotheticalAccountLiquidityInternal( address account, BToken bTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; uint ratingValue = birdOracle.getAddressRating(account); BToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { BToken asset = assets[i]; (oErr, vars.bTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == bTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } }
8,970,129
pragma solidity 0.5.13; import "@daostack/infra/contracts/votingMachines/IntVoteInterface.sol"; import "@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol"; import "./UniversalScheme.sol"; import "../votingMachines/VotingMachineCallbacks.sol"; /** * @title A scheme for proposing and rewarding contributions to an organization * @dev An agent can ask an organization to recognize a contribution and reward * him with token, reputation, ether or any combination. */ contract ContributionReward is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface { using SafeMath for uint256; event NewContributionProposal( address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, string _descriptionHash, uint256[5] _rewards, IERC20 _externalToken, address _beneficiary ); event ProposalExecuted( address indexed _avatar, bytes32 indexed _proposalId, int256 _param ); event RedeemEther( address indexed _avatar, bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount ); event RedeemExternalToken( address indexed _avatar, bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount ); // A struct holding the data for a contribution proposal struct ContributionProposal { uint256 ethReward; IERC20 externalToken; uint256 externalTokenReward; address payable beneficiary; uint256 periodLength; uint256 numberOfPeriods; uint256 executionTime; uint256[4] redeemedPeriods; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address => mapping(bytes32 => ContributionProposal)) public organizationsProposals; // A mapping from hashes to parameters (use to store a particular configuration on the controller) struct Parameters { bytes32 voteApproveParams; IntVoteInterface intVote; } // A mapping from hashes to parameters (use to store a particular configuration on the controller) mapping(bytes32 => Parameters) public parameters; /** * @dev execution of proposals, can only be called by the voting machine in which the vote is held. * @param _proposalId the ID of the voting in the voting machine * @param _param a parameter of the voting result, 1 yes and 2 is no. */ function executeProposal(bytes32 _proposalId, int256 _param) external onlyVotingMachine(_proposalId) returns (bool) { ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; require( organizationsProposals[address(proposal.avatar)][_proposalId] .executionTime == 0 ); require( organizationsProposals[address(proposal.avatar)][_proposalId] .beneficiary != address(0) ); // Check if vote was successful: if (_param == 1) { // solhint-disable-next-line not-rely-on-time organizationsProposals[address(proposal.avatar)][_proposalId] .executionTime = now; } emit ProposalExecuted(address(proposal.avatar), _proposalId, _param); return true; } /** * @dev hash the parameters, save them if necessary, and return the hash value */ function setParameters( bytes32 _voteApproveParams, IntVoteInterface _intVote ) public returns (bytes32) { bytes32 paramsHash = getParametersHash(_voteApproveParams, _intVote); parameters[paramsHash].voteApproveParams = _voteApproveParams; parameters[paramsHash].intVote = _intVote; return paramsHash; } /** * @dev Submit a proposal for a reward for a contribution: * @param _avatar Avatar of the organization that the contribution was made for * @param _descriptionHash A hash of the proposal's description * @param _rewards rewards array: * rewards[0] - Amount of tokens requested per period * rewards[1] - Amount of ETH requested per period * rewards[2] - Amount of external tokens requested per period * rewards[3] - Period length - if set to zero it allows immediate redeeming after execution. * rewards[4] - Number of periods * @param _beneficiary Who gets the rewards */ function proposeContributionReward( Avatar _avatar, string memory _descriptionHash, int256, uint256[5] memory _rewards, IERC20 _externalToken, address payable _beneficiary ) public returns (bytes32) { validateProposalParams( _rewards); Parameters memory controllerParams = parameters[getParametersFromController(_avatar)]; bytes32 contributionId = controllerParams.intVote.propose( 2, controllerParams.voteApproveParams, msg.sender, address(_avatar) ); address payable beneficiary = _beneficiary; if (beneficiary == address(0)) { beneficiary = msg.sender; } ContributionProposal memory proposal = ContributionProposal({ ethReward: _rewards[1], externalToken: _externalToken, externalTokenReward: _rewards[2], beneficiary: beneficiary, periodLength: _rewards[3], numberOfPeriods: _rewards[4], executionTime: 0, redeemedPeriods: [uint256(0), uint256(0), uint256(0), uint256(0)] }); organizationsProposals[address(_avatar)][contributionId] = proposal; emit NewContributionProposal( address(_avatar), contributionId, address(controllerParams.intVote), _descriptionHash, _rewards, _externalToken, beneficiary ); proposalsInfo[address( controllerParams.intVote )][contributionId] = ProposalInfo({ blockNumber: block.number, avatar: _avatar }); return contributionId; } /** * @dev RedeemEther reward for proposal * @param _proposalId the ID of the voting in the voting machine * @param _avatar address of the controller * @return amount ether redeemed amount */ function redeemEther(bytes32 _proposalId, Avatar _avatar) public returns (uint256 amount) { ContributionProposal memory _proposal = organizationsProposals[address( _avatar )][_proposalId]; ContributionProposal storage proposal = organizationsProposals[address( _avatar )][_proposalId]; require(proposal.executionTime != 0); uint256 periodsToPay = getPeriodsToPay( _proposalId, address(_avatar), 2 ); //set proposal rewards to zero to prevent reentrancy attack. proposal.ethReward = 0; amount = periodsToPay.mul(_proposal.ethReward); if (amount > 0) { require( Controller(_avatar.owner()).sendEther( amount, _proposal.beneficiary, _avatar ) ); proposal.redeemedPeriods[2] = proposal.redeemedPeriods[2].add( periodsToPay ); emit RedeemEther( address(_avatar), _proposalId, _proposal.beneficiary, amount ); } //restore proposal reward. proposal.ethReward = _proposal.ethReward; } /** * @dev RedeemNativeToken reward for proposal * @param _proposalId the ID of the voting in the voting machine * @param _avatar address of the controller * @return amount the external token redeemed amount */ function redeemExternalToken(bytes32 _proposalId, Avatar _avatar) public returns (uint256 amount) { ContributionProposal memory _proposal = organizationsProposals[address( _avatar )][_proposalId]; ContributionProposal storage proposal = organizationsProposals[address( _avatar )][_proposalId]; require(proposal.executionTime != 0); uint256 periodsToPay = getPeriodsToPay( _proposalId, address(_avatar), 3 ); //set proposal rewards to zero to prevent reentrancy attack. proposal.externalTokenReward = 0; if ( proposal.externalToken != IERC20(0) && _proposal.externalTokenReward > 0 ) { amount = periodsToPay.mul(_proposal.externalTokenReward); if (amount > 0) { require( Controller(_avatar.owner()).externalTokenTransfer( _proposal.externalToken, _proposal.beneficiary, amount, _avatar ) ); proposal.redeemedPeriods[3] = proposal.redeemedPeriods[3].add( periodsToPay ); emit RedeemExternalToken( address(_avatar), _proposalId, _proposal.beneficiary, amount ); } } //restore proposal reward. proposal.externalTokenReward = _proposal.externalTokenReward; } /** * @dev redeem rewards for proposal * @param _proposalId the ID of the voting in the voting machine * @param _avatar address of the controller * @param _whatToRedeem whatToRedeem array: * whatToRedeem[0] - reputation * whatToRedeem[1] - nativeTokenReward * whatToRedeem[2] - Ether * whatToRedeem[3] - ExternalToken * @return result boolean array for each redeem type. */ function redeem( bytes32 _proposalId, Avatar _avatar, bool[4] memory _whatToRedeem ) public returns ( uint256 etherReward, uint256 externalTokenReward ) { if (_whatToRedeem[2]) { etherReward = redeemEther(_proposalId, _avatar); } if (_whatToRedeem[3]) { externalTokenReward = redeemExternalToken(_proposalId, _avatar); } } /** * @dev getPeriodsToPay return the periods left to be paid for reputation,nativeToken,ether or externalToken. * The function ignore the reward amount to be paid (which can be zero). * @param _proposalId the ID of the voting in the voting machine * @param _avatar address of the controller * @param _redeemType - the type of the reward : * 0 - reputation * 1 - nativeTokenReward * 2 - Ether * 3 - ExternalToken * @return periods left to be paid. */ function getPeriodsToPay( bytes32 _proposalId, address _avatar, uint256 _redeemType ) public view returns (uint256) { require(_redeemType <= 3, "should be in the redeemedPeriods range"); ContributionProposal memory _proposal = organizationsProposals[_avatar][_proposalId]; if (_proposal.executionTime == 0) return 0; uint256 periodsFromExecution; if (_proposal.periodLength > 0) { // solhint-disable-next-line not-rely-on-time periodsFromExecution = (now.sub(_proposal.executionTime)) / (_proposal.periodLength); } uint256 periodsToPay; if ( (_proposal.periodLength == 0) || (periodsFromExecution >= _proposal.numberOfPeriods) ) { periodsToPay = _proposal.numberOfPeriods.sub( _proposal.redeemedPeriods[_redeemType] ); } else { periodsToPay = periodsFromExecution.sub( _proposal.redeemedPeriods[_redeemType] ); } return periodsToPay; } /** * @dev getRedeemedPeriods return the already redeemed periods for reputation, nativeToken, ether or externalToken. * @param _proposalId the ID of the voting in the voting machine * @param _avatar address of the controller * @param _redeemType - the type of the reward : * 0 - reputation * 1 - nativeTokenReward * 2 - Ether * 3 - ExternalToken * @return redeemed period. */ function getRedeemedPeriods( bytes32 _proposalId, address _avatar, uint256 _redeemType ) public view returns (uint256) { return organizationsProposals[_avatar][_proposalId] .redeemedPeriods[_redeemType]; } function getProposalEthReward(bytes32 _proposalId, address _avatar) public view returns (uint256) { return organizationsProposals[_avatar][_proposalId].ethReward; } function getProposalExternalTokenReward( bytes32 _proposalId, address _avatar ) public view returns (uint256) { return organizationsProposals[_avatar][_proposalId].externalTokenReward; } function getProposalExternalToken(bytes32 _proposalId, address _avatar) public view returns (address) { return address(organizationsProposals[_avatar][_proposalId].externalToken); } function getProposalExecutionTime(bytes32 _proposalId, address _avatar) public view returns (uint256) { return organizationsProposals[_avatar][_proposalId].executionTime; } /** * @dev return a hash of the given parameters * @param _voteApproveParams parameters for the voting machine used to approve a contribution * @param _intVote the voting machine used to approve a contribution * @return a hash of the parameters */ function getParametersHash( bytes32 _voteApproveParams, IntVoteInterface _intVote ) public pure returns (bytes32) { return (keccak256(abi.encodePacked(_voteApproveParams, _intVote))); } /** * @dev validateProposalParams validate proposal's rewards parameters. * The function check for potential overflow upon proposal's redeem. * The function reverts if the params are not valid. * @param _rewards rewards array: * rewards[0] - Amount of tokens requested per period * rewards[1] - Amount of ETH requested per period * rewards[2] - Amount of external tokens requested per period * rewards[3] - Period length - if set to zero it allows immediate redeeming after execution. * rewards[4] - Number of periods */ function validateProposalParams( uint256[5] memory _rewards ) private pure { //changed for sngls dao require(_rewards[0] == 0, "SGT token functionality is blocked."); require( ((_rewards[3] > 0) || (_rewards[4] == 1)), "periodLength equal 0 require numberOfPeriods to be 1" ); if (_rewards[4] > 0) { // This is the only case of overflow not detected by the check below //check that numberOfPeriods * tokenReward will not overflow require( (_rewards[4] * _rewards[0]) / _rewards[4] == _rewards[0], "numberOfPeriods * tokenReward will overflow" ); //check that numberOfPeriods * ethReward will not overflow require( (_rewards[4] * _rewards[1]) / _rewards[4] == _rewards[1], "numberOfPeriods * ethReward will overflow" ); //check that numberOfPeriods * texternalTokenReward will not overflow require( (_rewards[4] * _rewards[2]) / _rewards[4] == _rewards[2], "numberOfPeriods * texternalTokenReward will overflow" ); } } }
RedeemNativeToken reward for proposal _proposalId the ID of the voting in the voting machine _avatar address of the controller return amount the external token redeemed amount/set proposal rewards to zero to prevent reentrancy attack.
function redeemExternalToken(bytes32 _proposalId, Avatar _avatar) public returns (uint256 amount) { ContributionProposal memory _proposal = organizationsProposals[address( _avatar )][_proposalId]; ContributionProposal storage proposal = organizationsProposals[address( _avatar )][_proposalId]; require(proposal.executionTime != 0); uint256 periodsToPay = getPeriodsToPay( _proposalId, address(_avatar), 3 ); proposal.externalTokenReward = 0; if ( proposal.externalToken != IERC20(0) && _proposal.externalTokenReward > 0 ) { amount = periodsToPay.mul(_proposal.externalTokenReward); if (amount > 0) { require( Controller(_avatar.owner()).externalTokenTransfer( _proposal.externalToken, _proposal.beneficiary, amount, _avatar ) ); proposal.redeemedPeriods[3] = proposal.redeemedPeriods[3].add( periodsToPay ); emit RedeemExternalToken( address(_avatar), _proposalId, _proposal.beneficiary, amount ); } } }
12,873,257
// Project: AleHub // v1, 2018-05-24 // This code is the property of CryptoB2B.io // Copying in whole or in part is prohibited. // Authors: Ivan Fedorov and Dmitry Borodin // Do you want the same TokenSale platform? www.cryptob2b.io // *.sol in 1 file - https://cryptob2b.io/solidity/alehub/ pragma solidity ^0.4.21; contract GuidedByRoles { IRightAndRoles public rightAndRoles; function GuidedByRoles(IRightAndRoles _rightAndRoles) public { rightAndRoles = _rightAndRoles; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function minus(uint256 a, uint256 b) internal pure returns (uint256) { if (b>=a) return 0; return a - b; } } contract Crowdsale is GuidedByRoles{ // (A1) // The main contract for the sale and management of rounds. // 0000000000000000000000000000000000000000000000000000000000000000 uint256 constant USER_UNPAUSE_TOKEN_TIMEOUT = 60 days; uint256 constant FORCED_REFUND_TIMEOUT1 = 400 days; uint256 constant FORCED_REFUND_TIMEOUT2 = 600 days; uint256 constant ROUND_PROLONGATE = 60 days; uint256 constant BURN_TOKENS_TIME = 90 days; using SafeMath for uint256; enum TokenSaleType {round1, round2} TokenSaleType public TokenSale = TokenSaleType.round1; ICreator public creator; bool isBegin=false; IToken public token; IAllocation public allocation; IFinancialStrategy public financialStrategy; bool public isFinalized; bool public isInitialized; bool public isPausedCrowdsale; bool public chargeBonuses; bool public canFirstMint=true; struct Bonus { uint256 value; uint256 procent; uint256 freezeTime; } struct Profit { uint256 percent; uint256 duration; } struct Freezed { uint256 value; uint256 dateTo; } Bonus[] public bonuses; Profit[] public profits; uint256 public startTime= 1527206400; uint256 public endTime = 1529971199; uint256 public renewal; // How many tokens (excluding the bonus) are transferred to the investor in exchange for 1 ETH // **THOUSANDS** 10^18 for human, *10**18 for Solidity, 1e18 for MyEtherWallet (MEW). // Example: if 1ETH = 40.5 Token ==> use 40500 finney uint256 public rate = 2333 ether; // $0.1 (ETH/USD=$500) // ETH/USD rate in US$ // **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: ETH/USD=$1000 ==> use 1000*10**18 (Solidity) or 1000 ether or 1000e18 (MEW) uint256 public exchange = 700 ether; // If the round does not attain this value before the closing date, the round is recognized as a // failure and investors take the money back (the founders will not interfere in any way). // **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: softcap=15ETH ==> use 15*10**18 (Solidity) or 15e18 (MEW) uint256 public softCap = 0; // The maximum possible amount of income // **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: hardcap=123.45ETH ==> use 123450*10**15 (Solidity) or 12345e15 (MEW) uint256 public hardCap = 4285 ether; // $31M (ETH/USD=$500) // If the last payment is slightly higher than the hardcap, then the usual contracts do // not accept it, because it goes beyond the hardcap. However it is more reasonable to accept the // last payment, very slightly raising the hardcap. The value indicates by how many ETH the // last payment can exceed the hardcap to allow it to be paid. Immediately after this payment, the // round closes. The funders should write here a small number, not more than 1% of the CAP. // Can be equal to zero, to cancel. // **QUINTILLIONS** 10^18 / *10**18 / 1e18 uint256 public overLimit = 20 ether; // The minimum possible payment from an investor in ETH. Payments below this value will be rejected. // **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: minPay=0.1ETH ==> use 100*10**15 (Solidity) or 100e15 (MEW) uint256 public minPay = 43 finney; uint256 public maxAllProfit = 40; // max time bonus=20%, max value bonus=10%, maxAll=10%+20% uint256 public ethWeiRaised; uint256 public nonEthWeiRaised; uint256 public weiRound1; uint256 public tokenReserved; uint256 public totalSaledToken; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event Finalized(); event Initialized(); event PaymentedInOtherCurrency(uint256 token, uint256 value); event ExchangeChanged(uint256 indexed oldExchange, uint256 indexed newExchange); function Crowdsale(ICreator _creator,IToken _token) GuidedByRoles(_creator.getRightAndRoles()) public { creator=_creator; token = _token; } // Setting the current rate ETH/USD // function changeExchange(uint256 _ETHUSD) public { // require(rightAndRoles.onlyRoles(msg.sender,18)); // require(_ETHUSD >= 1 ether); // emit ExchangeChanged(exchange,_ETHUSD); // softCap=softCap.mul(exchange).div(_ETHUSD); // QUINTILLIONS // hardCap=hardCap.mul(exchange).div(_ETHUSD); // QUINTILLIONS // minPay=minPay.mul(exchange).div(_ETHUSD); // QUINTILLIONS // // rate=rate.mul(_ETHUSD).div(exchange); // QUINTILLIONS // // for (uint16 i = 0; i < bonuses.length; i++) { // bonuses[i].value=bonuses[i].value.mul(exchange).div(_ETHUSD); // QUINTILLIONS // } // bytes32[] memory params = new bytes32[](2); // params[0] = bytes32(exchange); // params[1] = bytes32(_ETHUSD); // financialStrategy.setup(5, params); // // exchange=_ETHUSD; // // } // Setting of basic parameters, analog of class constructor // @ Do I have to use the function see your scenario // @ When it is possible to call before Round 1/2 // @ When it is launched automatically - // @ Who can call the function admins function begin() public { require(rightAndRoles.onlyRoles(msg.sender,22)); if (isBegin) return; isBegin=true; financialStrategy = creator.createFinancialStrategy(); token.setUnpausedWallet(rightAndRoles.wallets(1,0), true); token.setUnpausedWallet(rightAndRoles.wallets(3,0), true); token.setUnpausedWallet(rightAndRoles.wallets(4,0), true); token.setUnpausedWallet(rightAndRoles.wallets(5,0), true); token.setUnpausedWallet(rightAndRoles.wallets(6,0), true); bonuses.push(Bonus(1429 finney, 2,0)); bonuses.push(Bonus(14286 finney, 5,0)); bonuses.push(Bonus(142857 finney, 10,0)); profits.push(Profit(25,100 days)); } // Issue of tokens for the zero round, it is usually called: private pre-sale (Round 0) // @ Do I have to use the function may be // @ When it is possible to call before Round 1/2 // @ When it is launched automatically - // @ Who can call the function admins function firstMintRound0(uint256 _amount /* QUINTILLIONS! */) public { require(rightAndRoles.onlyRoles(msg.sender,6)); require(canFirstMint); begin(); token.mint(rightAndRoles.wallets(3,0),_amount); } // info function totalSupply() external view returns (uint256){ return token.totalSupply(); } // Returns the name of the current round in plain text. Constant. function getTokenSaleType() external view returns(string){ return (TokenSale == TokenSaleType.round1)?'round1':'round2'; } // Transfers the funds of the investor to the contract of return of funds. Internal. function forwardFunds(address _beneficiary) internal { financialStrategy.deposit.value(msg.value)(_beneficiary); } // Check for the possibility of buying tokens. Inside. Constant. function validPurchase() internal view returns (bool) { // The round started and did not end bool withinPeriod = (now > startTime && now < endTime.add(renewal)); // Rate is greater than or equal to the minimum bool nonZeroPurchase = msg.value >= minPay; // hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit); // round is initialized and no "Pause of trading" is set return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isFinalized && !isPausedCrowdsale; } // Check for the ability to finalize the round. Constant. function hasEnded() public view returns (bool) { bool isAdmin = rightAndRoles.onlyRoles(msg.sender,6); bool timeReached = now > endTime.add(renewal); bool capReached = weiRaised() >= hardCap; return (timeReached || capReached || (isAdmin && goalReached())) && isInitialized && !isFinalized; } // Finalize. Only available to the Manager and the Beneficiary. If the round failed, then // anyone can call the finalization to unlock the return of funds to investors // You must call a function to finalize each round (after the Round1 & after the Round2) // @ Do I have to use the function yes // @ When it is possible to call after end of Round1 & Round2 // @ When it is launched automatically no // @ Who can call the function admins or anybody (if round is failed) function finalize() public { // bool isAdmin = rightAndRoles.onlyRoles(msg.sender,6); // require(isAdmin|| !goalReached()); // require(!isFinalized && isInitialized); // require(hasEnded() || (isAdmin && goalReached())); require(hasEnded()); isFinalized = true; finalization(); emit Finalized(); } // The logic of finalization. Internal // @ Do I have to use the function no // @ When it is possible to call - // @ When it is launched automatically after end of round // @ Who can call the function - function finalization() internal { bytes32[] memory params = new bytes32[](0); // If the goal of the achievement if (goalReached()) { financialStrategy.setup(1,params);//Для контракта Buz деньги не возвращает. // if there is anything to give if (tokenReserved > 0) { token.mint(rightAndRoles.wallets(3,0),tokenReserved); // Reset the counter tokenReserved = 0; } // If the finalization is Round 1 if (TokenSale == TokenSaleType.round1) { // Reset settings isInitialized = false; isFinalized = false; if(financialStrategy.freeCash() == 0){ rightAndRoles.setManagerPowerful(true); } // Switch to the second round (to Round2) TokenSale = TokenSaleType.round2; // Reset the collection counter weiRound1 = weiRaised(); ethWeiRaised = 0; nonEthWeiRaised = 0; } else // If the second round is finalized { // Permission to collect tokens to those who can pick them up chargeBonuses = true; totalSaledToken = token.totalSupply(); //partners = true; } } else // If they failed round { financialStrategy.setup(3,params); } } // The Manager freezes the tokens for the Team. // You must call a function to finalize Round 2 (only after the Round2) // @ Do I have to use the function yes // @ When it is possible to call Round2 // @ When it is launched automatically - // @ Who can call the function admins function finalize2() public { require(rightAndRoles.onlyRoles(msg.sender,6)); require(chargeBonuses); chargeBonuses = false; allocation = creator.createAllocation(token, now + 1 years /* stage N1 */,0/* not need*/); token.setUnpausedWallet(allocation, true); // Team = %, Founders = %, Fund = % TOTAL = % allocation.addShare(rightAndRoles.wallets(7,0),100,100); // all 100% - first year //allocation.addShare(wallets[uint8(Roles.founders)], 10, 50); // only 50% - first year, stage N1 (and +50 for stage N2) // 2% - bounty wallet token.mint(rightAndRoles.wallets(5,0), totalSaledToken.mul(2).div(77)); // 10% - company token.mint(rightAndRoles.wallets(6,0), totalSaledToken.mul(10).div(77)); // 13% - team token.mint(allocation, totalSaledToken.mul(11).div(77)); } // Initializing the round. Available to the manager. After calling the function, // the Manager loses all rights: Manager can not change the settings (setup), change // wallets, prevent the beginning of the round, etc. You must call a function after setup // for the initial round (before the Round1 and before the Round2) // @ Do I have to use the function yes // @ When it is possible to call before each round // @ When it is launched automatically - // @ Who can call the function admins function initialize() public { require(rightAndRoles.onlyRoles(msg.sender,6)); // If not yet initialized require(!isInitialized); begin(); // And the specified start time has not yet come // If initialization return an error, check the start date! require(now <= startTime); initialization(); emit Initialized(); renewal = 0; isInitialized = true; canFirstMint = false; } function initialization() internal { bytes32[] memory params = new bytes32[](0); rightAndRoles.setManagerPowerful(false); if (financialStrategy.state() != IFinancialStrategy.State.Active){ financialStrategy.setup(2,params); } } // // @ Do I have to use the function // @ When it is possible to call // @ When it is launched automatically // @ Who can call the function function getPartnerCash(uint8 _user, bool _calc) external { if(_calc) calcFin(); financialStrategy.getPartnerCash(_user, msg.sender); } function getBeneficiaryCash(bool _calc) public { require(rightAndRoles.onlyRoles(msg.sender,22)); if(_calc) calcFin(); financialStrategy.getBeneficiaryCash(); if(!isInitialized && financialStrategy.freeCash() == 0) rightAndRoles.setManagerPowerful(true); } function claimRefund() external{ financialStrategy.refund(msg.sender); } function calcFin() public { bytes32[] memory params = new bytes32[](2); params[0] = bytes32(weiTotalRaised()); params[1] = bytes32(msg.sender); financialStrategy.setup(4,params); } function calcAndGet() public { require(rightAndRoles.onlyRoles(msg.sender,22)); getBeneficiaryCash(true); for (uint8 i=0; i<0; i++) { // <-- TODO check financialStrategy.wallets.length financialStrategy.getPartnerCash(i, msg.sender); } } // We check whether we collected the necessary minimum funds. Constant. function goalReached() public view returns (bool) { return weiRaised() >= softCap; } // Customize. The arguments are described in the constructor above. // @ Do I have to use the function yes // @ When it is possible to call before each rond // @ When it is launched automatically - // @ Who can call the function admins function setup(uint256 _startTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap, uint256 _rate, uint256 _exchange, uint256 _maxAllProfit, uint256 _overLimit, uint256 _minPay, uint256[] _durationTB , uint256[] _percentTB, uint256[] _valueVB, uint256[] _percentVB, uint256[] _freezeTimeVB) public { require(rightAndRoles.onlyRoles(msg.sender,6)); require(!isInitialized); begin(); // Date and time are correct require(now <= _startTime); require(_startTime < _endTime); startTime = _startTime; endTime = _endTime; // The parameters are correct require(_softCap <= _hardCap); softCap = _softCap; hardCap = _hardCap; require(_rate > 0); rate = _rate; overLimit = _overLimit; minPay = _minPay; exchange = _exchange; maxAllProfit = _maxAllProfit; require(_valueVB.length == _percentVB.length && _valueVB.length == _freezeTimeVB.length); bonuses.length = _valueVB.length; for(uint256 i = 0; i < _valueVB.length; i++){ bonuses[i] = Bonus(_valueVB[i],_percentVB[i],_freezeTimeVB[i]); } require(_percentTB.length == _durationTB.length); profits.length = _percentTB.length; for( i = 0; i < _percentTB.length; i++){ profits[i] = Profit(_percentTB[i],_durationTB[i]); } } // Collected funds for the current round. Constant. function weiRaised() public constant returns(uint256){ return ethWeiRaised.add(nonEthWeiRaised); } // Returns the amount of fees for both phases. Constant. function weiTotalRaised() public constant returns(uint256){ return weiRound1.add(weiRaised()); } // Returns the percentage of the bonus on the current date. Constant. function getProfitPercent() public constant returns (uint256){ return getProfitPercentForData(now); } // Returns the percentage of the bonus on the given date. Constant. function getProfitPercentForData(uint256 _timeNow) public constant returns (uint256){ uint256 allDuration; for(uint8 i = 0; i < profits.length; i++){ allDuration = allDuration.add(profits[i].duration); if(_timeNow < startTime.add(allDuration)){ return profits[i].percent; } } return 0; } function getBonuses(uint256 _value) public constant returns (uint256,uint256,uint256){ if(bonuses.length == 0 || bonuses[0].value > _value){ return (0,0,0); } uint16 i = 1; for(i; i < bonuses.length; i++){ if(bonuses[i].value > _value){ break; } } return (bonuses[i-1].value,bonuses[i-1].procent,bonuses[i-1].freezeTime); } // The ability to quickly check Round1 (only for Round1, only 1 time). Completes the Round1 by // transferring the specified number of tokens to the Accountant's wallet. Available to the Manager. // Use only if this is provided by the script and white paper. In the normal scenario, it // does not call and the funds are raised normally. We recommend that you delete this // function entirely, so as not to confuse the auditors. Initialize & Finalize not needed. // ** QUINTILIONS ** 10^18 / 1**18 / 1e18 // @ Do I have to use the function no, see your scenario // @ When it is possible to call after Round0 and before Round2 // @ When it is launched automatically - // @ Who can call the function admins // function fastTokenSale(uint256 _totalSupply) external { // onlyAdmin(false); // require(TokenSale == TokenSaleType.round1 && !isInitialized); // token.mint(wallets[uint8(Roles.accountant)], _totalSupply); // TokenSale = TokenSaleType.round2; // } // Remove the "Pause of exchange". Available to the manager at any time. If the // manager refuses to remove the pause, then 30-120 days after the successful // completion of the TokenSale, anyone can remove a pause and allow the exchange to continue. // The manager does not interfere and will not be able to delay the term. // He can only cancel the pause before the appointed time. // @ Do I have to use the function YES YES YES // @ When it is possible to call after end of ICO // @ When it is launched automatically - // @ Who can call the function admins or anybody function tokenUnpause() external { require(rightAndRoles.onlyRoles(msg.sender,2) || (now > endTime.add(renewal).add(USER_UNPAUSE_TOKEN_TIMEOUT) && TokenSale == TokenSaleType.round2 && isFinalized && goalReached())); token.setPause(false); } // Enable the "Pause of exchange". Available to the manager until the TokenSale is completed. // The manager cannot turn on the pause, for example, 3 years after the end of the TokenSale. // @ Do I have to use the function no // @ When it is possible to call while Round2 not ended // @ When it is launched automatically before any rounds // @ Who can call the function admins function tokenPause() public { require(rightAndRoles.onlyRoles(msg.sender,6)); require(!isFinalized); token.setPause(true); } // Pause of sale. Available to the manager. // @ Do I have to use the function no // @ When it is possible to call during active rounds // @ When it is launched automatically - // @ Who can call the function admins function setCrowdsalePause(bool mode) public { require(rightAndRoles.onlyRoles(msg.sender,6)); isPausedCrowdsale = mode; } // For example - After 5 years of the project's existence, all of us suddenly decided collectively // (company + investors) that it would be more profitable for everyone to switch to another smart // contract responsible for tokens. The company then prepares a new token, investors // disassemble, study, discuss, etc. After a general agreement, the manager allows any investor: // - to burn the tokens of the previous contract // - generate new tokens for a new contract // It is understood that after a general solution through this function all investors // will collectively (and voluntarily) move to a new token. // @ Do I have to use the function no // @ When it is possible to call only after ICO! // @ When it is launched automatically - // @ Who can call the function admins function moveTokens(address _migrationAgent) public { require(rightAndRoles.onlyRoles(msg.sender,6)); token.setMigrationAgent(_migrationAgent); } // @ Do I have to use the function no // @ When it is possible to call only after ICO! // @ When it is launched automatically - // @ Who can call the function admins function migrateAll(address[] _holders) public { require(rightAndRoles.onlyRoles(msg.sender,6)); token.migrateAll(_holders); } // The beneficiary at any time can take rights in all roles and prescribe his wallet in all the // rollers. Thus, he will become the recipient of tokens for the role of Accountant, // Team, etc. Works at any time. // @ Do I have to use the function no // @ When it is possible to call any time // @ When it is launched automatically - // @ Who can call the function only Beneficiary // function resetAllWallets() external{ // address _beneficiary = wallets[uint8(Roles.beneficiary)]; // require(msg.sender == _beneficiary); // for(uint8 i = 0; i < wallets.length; i++){ // wallets[i] = _beneficiary; // } // token.setUnpausedWallet(_beneficiary, true); // } // Burn the investor tokens, if provided by the ICO scenario. Limited time available - BURN_TOKENS_TIME // For people who ignore the KYC/AML procedure during 30 days after payment: money back and burning tokens. // ***CHECK***SCENARIO*** // @ Do I have to use the function no // @ When it is possible to call any time // @ When it is launched automatically - // @ Who can call the function admin function massBurnTokens(address[] _beneficiary, uint256[] _value) external { require(rightAndRoles.onlyRoles(msg.sender,6)); require(endTime.add(renewal).add(BURN_TOKENS_TIME) > now); require(_beneficiary.length == _value.length); for(uint16 i; i<_beneficiary.length; i++) { token.burn(_beneficiary[i],_value[i]); } } // Extend the round time, if provided by the script. Extend the round only for // a limited number of days - ROUND_PROLONGATE // ***CHECK***SCENARIO*** // @ Do I have to use the function no // @ When it is possible to call during active round // @ When it is launched automatically - // @ Who can call the function admins function prolong(uint256 _duration) external { require(rightAndRoles.onlyRoles(msg.sender,6)); require(now > startTime && now < endTime.add(renewal) && isInitialized && !isFinalized); renewal = renewal.add(_duration); require(renewal <= ROUND_PROLONGATE); } // If a little more than a year has elapsed (Round2 start date + 400 days), a smart contract // will allow you to send all the money to the Beneficiary, if any money is present. This is // possible if you mistakenly launch the Round2 for 30 years (not 30 days), investors will transfer // money there and you will not be able to pick them up within a reasonable time. It is also // possible that in our checked script someone will make unforeseen mistakes, spoiling the // finalization. Without finalization, money cannot be returned. This is a rescue option to // get around this problem, but available only after a year (400 days). // Another reason - the TokenSale was a failure, but not all ETH investors took their money during the year after. // Some investors may have lost a wallet key, for example. // The method works equally with the Round1 and Round2. When the Round1 starts, the time for unlocking // the distructVault begins. If the TokenSale is then started, then the term starts anew from the first day of the TokenSale. // Next, act independently, in accordance with obligations to investors. // Within 400 days (FORCED_REFUND_TIMEOUT1) of the start of the Round, if it fails only investors can take money. After // the deadline this can also include the company as well as investors, depending on who is the first to use the method. // @ Do I have to use the function no // @ When it is possible to call - // @ When it is launched automatically - // @ Who can call the function beneficiary & manager function distructVault() public { bytes32[] memory params = new bytes32[](1); params[0] = bytes32(msg.sender); if (rightAndRoles.onlyRoles(msg.sender,4) && (now > startTime.add(FORCED_REFUND_TIMEOUT1))) { financialStrategy.setup(0,params); } if (rightAndRoles.onlyRoles(msg.sender,2) && (now > startTime.add(FORCED_REFUND_TIMEOUT2))) { financialStrategy.setup(0,params); } } // We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC). // Perhaps other types of cryptocurrency - see the original terms in the white paper and on the TokenSale website. // We release tokens on Ethereum. During the Round1 and Round2 with a smart contract, you directly transfer // the tokens there and immediately, with the same transaction, receive tokens in your wallet. // When paying in any other currency, for example in BTC, we accept your money via one common wallet. // Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart // contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis. // The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract // monitors softcap and hardcap, so as not to go beyond this framework. // In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several // transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total. // In this case, we will refund all the amounts above, in order not to exceed the hardcap. // Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published // everywhere (in a white paper, on the TokenSale website, on Telegram, on Bitcointalk, in this code, etc.) // Anyone interested can check that the administrator of the smart contract writes down exactly the amount // in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in // BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to // paymentsInOtherCurrency however, this threat is leveled. // Any user can check the amounts in BTC and the variable of the smart contract that accounts for this // (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract // on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the TokenSale, // simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection) // and the actual transactions in BTC. The company strictly adheres to the described principles of openness. // The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you // cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as // brakes on the Ethereum network, this operation may be difficult. You should only worry if the // administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet // receives significant amounts. // This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap. // ** QUINTILLIONS ** 10^18 / 1**18 / 1e18 // @ Do I have to use the function no // @ When it is possible to call during active rounds // @ When it is launched automatically every day from cryptob2b token software // @ Who can call the function admins + observer function paymentsInOtherCurrency(uint256 _token, uint256 _value) public { // **For audit** // BTC Wallet: 1D7qaRN6keGJKb5LracZYQEgCBaryZxVaE // BCH Wallet: 1CDRdTwvEyZD7qjiGUYxZQSf8n91q95xHU // DASH Wallet: XnjajDvQq1C7z2o4EFevRhejc6kRmX1NUp // LTC Wallet: LhHkiwVfoYEviYiLXP5pRK2S1QX5eGrotA require(rightAndRoles.onlyRoles(msg.sender,18)); //onlyAdmin(true); bool withinPeriod = (now >= startTime && now <= endTime.add(renewal)); bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit); require(withinPeriod && withinCap && isInitialized && !isFinalized); emit PaymentedInOtherCurrency(_token,_value); nonEthWeiRaised = _value; tokenReserved = _token; } function lokedMint(address _beneficiary, uint256 _value, uint256 _freezeTime) internal { if(_freezeTime > 0){ uint256 totalBloked = token.freezedTokenOf(_beneficiary).add(_value); uint256 pastDateUnfreeze = token.defrostDate(_beneficiary); uint256 newDateUnfreeze = _freezeTime.add(now); newDateUnfreeze = (pastDateUnfreeze > newDateUnfreeze ) ? pastDateUnfreeze : newDateUnfreeze; token.freezeTokens(_beneficiary,totalBloked,newDateUnfreeze); } token.mint(_beneficiary,_value); } // The function for obtaining smart contract funds in ETH. If all the checks are true, the token is // transferred to the buyer, taking into account the current bonus. function buyTokens(address _beneficiary) public payable { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 ProfitProcent = getProfitPercent(); uint256 value; uint256 percent; uint256 freezeTime; (value, percent, freezeTime) = getBonuses(weiAmount); Bonus memory curBonus = Bonus(value,percent,freezeTime); uint256 bonus = curBonus.procent; // -------------------------------------------------------------------------------------------- // *** Scenario 1 - select max from all bonuses + check maxAllProfit //uint256 totalProfit = (ProfitProcent < bonus) ? bonus : ProfitProcent; // *** Scenario 2 - sum both bonuses + check maxAllProfit uint256 totalProfit = bonus.add(ProfitProcent); // -------------------------------------------------------------------------------------------- totalProfit = (totalProfit > maxAllProfit) ? maxAllProfit : totalProfit; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate).mul(totalProfit.add(100)).div(100 ether); // update state ethWeiRaised = ethWeiRaised.add(weiAmount); lokedMint(_beneficiary, tokens, curBonus.freezeTime); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(_beneficiary);//forwardFunds(msg.sender); } // buyTokens alias function () public payable { buyTokens(msg.sender); } } contract ICreator{ function createAllocation(IToken _token, uint256 _unlockPart1, uint256 _unlockPart2) external returns (IAllocation); function createFinancialStrategy() external returns(IFinancialStrategy); function getRightAndRoles() external returns(IRightAndRoles); } contract IToken{ function setUnpausedWallet(address _wallet, bool mode) public; function mint(address _to, uint256 _amount) public returns (bool); function totalSupply() public view returns (uint256); function setPause(bool mode) public; function setMigrationAgent(address _migrationAgent) public; function migrateAll(address[] _holders) public; function burn(address _beneficiary, uint256 _value) public; function freezedTokenOf(address _beneficiary) public view returns (uint256 amount); function defrostDate(address _beneficiary) public view returns (uint256 Date); function freezeTokens(address _beneficiary, uint256 _amount, uint256 _when) public; } contract IFinancialStrategy{ enum State { Active, Refunding, Closed } State public state = State.Active; event Deposited(address indexed beneficiary, uint256 weiAmount); event Receive(address indexed beneficiary, uint256 weiAmount); event Refunded(address indexed beneficiary, uint256 weiAmount); event Started(); event Closed(); event RefundsEnabled(); function freeCash() view public returns(uint256); function deposit(address _beneficiary) external payable; function refund(address _investor) external; function setup(uint8 _state, bytes32[] _params) external; function getBeneficiaryCash() external; function getPartnerCash(uint8 _user, address _msgsender) external; } contract IAllocation { function addShare(address _beneficiary, uint256 _proportion, uint256 _percenForFirstPart) external; } contract IRightAndRoles { address[][] public wallets; mapping(address => uint16) public roles; event WalletChanged(address indexed newWallet, address indexed oldWallet, uint8 indexed role); event CloneChanged(address indexed wallet, uint8 indexed role, bool indexed mod); function changeWallet(address _wallet, uint8 _role) external; function setManagerPowerful(bool _mode) external; function onlyRoles(address _sender, uint16 _roleMask) view external returns(bool); }
Finalize. Only available to the Manager and the Beneficiary. If the round failed, then anyone can call the finalization to unlock the return of funds to investors You must call a function to finalize each round (after the Round1 & after the Round2) @ Do I have to use the function yes @ When it is possible to call after end of Round1 & Round2 @ When it is launched automatically no @ Who can call the function admins or anybody (if round is failed) bool isAdmin = rightAndRoles.onlyRoles(msg.sender,6); require(isAdmin|| !goalReached()); require(!isFinalized && isInitialized); require(hasEnded() || (isAdmin && goalReached()));
function finalize() public { require(hasEnded()); isFinalized = true; finalization(); emit Finalized(); }
11,869,827
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IFateRewardController.sol"; import "./IRewardSchedule.sol"; import "./MockLpToken.sol"; import "./IMockLpTokenFactory.sol"; // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once FATE is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract FateRewardControllerV2 is IFateRewardController { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfoV2 { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. bool isUpdated; // true if the user has been migrated from the v1 controller to v2 // // We do some fancy math here. Basically, any point in time, the amount of FATEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accumulatedFatePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accumulatedFatePerShare` (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. } IERC20 public override fate; address public override vault; IFateRewardController[] public oldControllers; // The emission scheduler that calculates fate per block over a given period IRewardSchedule public override emissionSchedule; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public override migrator; // Info of each pool. PoolInfo[] public override poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfoV2)) internal _userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public override totalAllocPoint = 0; // The block number when FATE mining starts. uint256 public override startBlock; IMockLpTokenFactory public mockLpTokenFactory; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event ClaimRewards(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmissionScheduleSet(address indexed emissionSchedule); event MigratorSet(address indexed migrator); event VaultSet(address indexed emissionSchedule); event PoolAdded(uint indexed pid, address indexed lpToken, uint allocPoint); event PoolAllocPointSet(uint indexed pid, uint allocPoint); constructor( IERC20 _fate, IRewardSchedule _emissionSchedule, address _vault, IFateRewardController[] memory _oldControllers, IMockLpTokenFactory _mockLpTokenFactory ) public { fate = _fate; emissionSchedule = _emissionSchedule; vault = _vault; oldControllers = _oldControllers; mockLpTokenFactory = _mockLpTokenFactory; startBlock = _oldControllers[0].startBlock(); } function poolLength() external override view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public override onlyOwner { for (uint i = 0; i < poolInfo.length; i++) { require( poolInfo[i].lpToken != _lpToken, "add: LP token already added" ); } if (_withUpdate) { massUpdatePools(); } require( _lpToken.balanceOf(address(this)) >= 0, "add: invalid LP token" ); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accumulatedFatePerShare : 0 }) ); emit PoolAdded(poolInfo.length - 1, address(_lpToken), _allocPoint); } // Update the given pool's FATE 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; emit PoolAllocPointSet(_pid, _allocPoint); } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public override onlyOwner { migrator = _migrator; emit MigratorSet(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 override { 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; } function migrate( IERC20 token ) external override returns (IERC20) { IFateRewardController oldController = IFateRewardController(address(0)); for (uint i = 0; i < oldControllers.length; i++) { if (address(oldControllers[i]) == msg.sender) { oldController = oldControllers[i]; } } require( address(oldController) != address(0), "migrate: invalid sender" ); IERC20 lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 accumulatedFatePerShare; uint oldPoolLength = oldController.poolLength(); for (uint i = 0; i < oldPoolLength; i++) { (lpToken, allocPoint, lastRewardBlock, accumulatedFatePerShare) = oldController.poolInfo(poolInfo.length); if (address(lpToken) == address(token)) { break; } } // transfer all of the tokens from the previous controller to here token.transferFrom(msg.sender, address(this), token.balanceOf(msg.sender)); poolInfo.push( PoolInfo({ lpToken : lpToken, allocPoint : allocPoint, lastRewardBlock : lastRewardBlock, accumulatedFatePerShare : accumulatedFatePerShare }) ); emit PoolAdded(poolInfo.length - 1, address(token), allocPoint); uint _totalAllocPoint = 0; for (uint i = 0; i < poolInfo.length; i++) { _totalAllocPoint = _totalAllocPoint.add(poolInfo[i].allocPoint); } totalAllocPoint = _totalAllocPoint; return IERC20(mockLpTokenFactory.create(address(lpToken), address(this))); } function userInfo( uint _pid, address _user ) public override view returns (uint amount, uint rewardDebt) { UserInfoV2 memory user = _userInfo[_pid][_user]; if (user.isUpdated) { return (user.amount, user.rewardDebt); } else { return oldControllers[0].userInfo(_pid, _user); } } function _getUserInfo( uint _pid, address _user ) internal view returns (IFateRewardController.UserInfo memory) { UserInfoV2 memory user = _userInfo[_pid][_user]; if (user.isUpdated) { return IFateRewardController.UserInfo(user.amount, user.rewardDebt); } else { (uint amount, uint rewardDebt) = oldControllers[0].userInfo(_pid, _user); return IFateRewardController.UserInfo(amount, rewardDebt); } } // View function to see pending FATE tokens on frontend. function pendingFate(uint256 _pid, address _user) external override view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, _user); uint256 accumulatedFatePerShare = pool.accumulatedFatePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, pool.lastRewardBlock, block.number); uint256 fateReward = fatePerBlock.mul(pool.allocPoint).div(totalAllocPoint); accumulatedFatePerShare = accumulatedFatePerShare.add(fateReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accumulatedFatePerShare).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); } } function getNewRewardPerBlock(uint pid1) public view returns (uint) { uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, block.number - 1, block.number); if (pid1 == 0) { return fatePerBlock; } else { return fatePerBlock.mul(poolInfo[pid1 - 1].allocPoint).div(totalAllocPoint); } } // 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 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, pool.lastRewardBlock, block.number); uint256 fateReward = fatePerBlock.mul(pool.allocPoint).div(totalAllocPoint); if (fateReward > 0) { fate.transferFrom(vault, address(this), fateReward); pool.accumulatedFatePerShare = pool.accumulatedFatePerShare.add(fateReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for FATE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); uint userBalance = user.amount.add(_amount); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : userBalance, rewardDebt : userBalance.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); uint userBalance = user.amount.sub(_amount); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : userBalance, rewardDebt : userBalance.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // claim any pending rewards from this pool, from msg.sender function claimReward(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); updatePool(_pid); uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : user.amount, rewardDebt : user.amount.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); } // claim any pending rewards from this pool, from msg.sender function claimRewards(uint256[] calldata _pids) external { for (uint i = 0; i < _pids.length; i++) { claimReward(_pids[i]); } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : 0, rewardDebt : 0, isUpdated : true }); } // Safe fate transfer function, just in case if rounding error causes pool to not have enough FATEs. function _safeFateTransfer(address _to, uint256 _amount) internal { uint256 fateBal = fate.balanceOf(address(this)); if (_amount > fateBal) { fate.transfer(_to, fateBal); } else { fate.transfer(_to, _amount); } } function setEmissionSchedule( IRewardSchedule _emissionSchedule ) public onlyOwner { // pro-rate the pools to the current block, before changing the schedule massUpdatePools(); emissionSchedule = _emissionSchedule; emit EmissionScheduleSet(address(_emissionSchedule)); } function setVault( address _vault ) public override onlyOwner { // pro-rate the pools to the current block, before changing the schedule vault = _vault; emit VaultSet(_vault); } }
claim any pending rewards from this pool, from msg.sender
function claimReward(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); updatePool(_pid); uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : user.amount, rewardDebt : user.amount.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); }
14,083,711
pragma solidity ^ 0.4.25; // ----------------------------------------------------------------------------------------------------------------- // // Recon® Token Teleportation Service v1.10 // // of BlockReconChain® // for ReconBank® // // ERC Token Standard #20 Interface // // ----------------------------------------------------------------------------------------------------------------- //. //" //. ::::::.. .,:::::: .,-::::: ... :::. ::: //. ;;;;``;;;; ;;;;'''' ,;;;'````' .;;;;;;;.`;;;;, `;;; //. [[[,/[[[' [[cccc [[[ ,[[ \[[,[[[[[. '[[ //. $$$$$$c $$"""" $$$ $$$, $$$$$$ "Y$c$$ //. 888b "88bo,888oo,__`88bo,__,o,"888,_ _,88P888 Y88 //. MMMM "W" """"YUMMM "YUMMMMMP" "YMMMMMP" MMM YM //. //. //" ----------------------------------------------------------------------------------------------------------------- // ¸.•*´¨) // ¸.•´ ¸.•´¸.•*´¨) ¸.•*¨) // ¸.•*´ (¸.•´ (¸.•` ¤ ReconBank.eth / ReconBank.com*´¨) // ¸.•´¸.•*´¨) // (¸.•´ ¸.•` // ¸.•´•.¸ // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // ----------------------------------------------------------------------------------------------------------------- // // Common ownership of : // ____ _ _ _____ _____ _ _ // | _ \| | | | | __ \ / ____| | (_) // | |_) | | ___ ___| | _| |__) |___ ___ ___ _ __ | | | |__ __ _ _ _ __ // | _ <| |/ _ \ / __| |/ / _ // _ \/ __/ _ \| '_ \| | | '_ \ / _` | | '_ \ // | |_) | | (_) | (__| <| | \ \ __/ (_| (_) | | | | |____| | | | (_| | | | | | // |____/|_|\___/ \___|_|\_\_| \_\___|\___\___/|_| |_|\_____|_| |_|\__,_|_|_| |_|® //' // ----------------------------------------------------------------------------------------------------------------- // // This contract is an order from : //' // ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ██╗██████╗ █████╗ ███╗ ██╗██╗ ██╗ ██████╗ ██████╗ ███╗ ███╗® // ██╔══██╗██╔════╝██╔════╝██╔═══██╗████╗ ██║██╔══██╗██╔══██╗████╗ ██║██║ ██╔╝ ██╔════╝██╔═══██╗████╗ ████║ // ██████╔╝█████╗ ██║ ██║ ██║██╔██╗ ██║██████╔╝███████║██╔██╗ ██║█████╔╝ ██║ ██║ ██║██╔████╔██║ // ██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╗██║██╔══██╗██╔══██║██║╚██╗██║██╔═██╗ ██║ ██║ ██║██║╚██╔╝██║ // ██║ ██║███████╗╚██████╗╚██████╔╝██║ ╚████║██████╔╝██║ ██║██║ ╚████║██║ ██╗██╗╚██████╗╚██████╔╝██║ ╚═╝ ██║ // ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝' // // ----------------------------------------------------------------------------------------------------------------- // // // Copyright MIT : // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // // Permission is hereby granted, free of charge, to // any person obtaining a copy of this software and // associated documentation files ReconCoin® Token // Teleportation Service, 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 SOFTWARE. // // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; // ----------------------------------------------------------------------------------------------------------------- // The new assembly support in Solidity makes writing helpers easy. // Many have complained how complex it is to use `ecrecover`, especially in conjunction // with the `eth_sign` RPC call. Here is a helper, which makes that a matter of a single call. // // Sample input parameters: // (with v=0) // "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad", // "0xaca7da997ad177f040240cdccf6905b71ab16b74434388c3a72f34fd25d6439346b2bac274ff29b48b3ea6e2d04c1336eaceafda3c53ab483fc3ff12fac3ebf200", // "0x0e5cb767cce09a7f3ca594df118aa519be5e2b5a" // // (with v=1) // "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad", // "0xdebaaa0cddb321b2dcaaf846d39605de7b97e77ba6106587855b9106cb10421561a22d94fa8b8a687ff9c911c844d1c016d1a685a9166858f9c7c1bc85128aca01", // "0x8743523d96a1b2cbe0c6909653a56da18ed484af" // // (The hash is a hash of "hello world".) // // Written by Alex Beregszaszi (@axic), use it under the terms of the MIT license. // ----------------------------------------------------------------------------------------------------------------- library ReconVerify { // Duplicate Soliditys ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but dont update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly cant access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function ecrecovery(bytes32 hash, bytes sig) public returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function verify(bytes32 hash, bytes sig, address signer) public returns (bool) { bool ret; address addr; (ret, addr) = ecrecovery(hash, sig); return ret == true && addr == signer; } function recover(bytes32 hash, bytes sig) internal returns (address addr) { bool ret; (ret, addr) = ecrecovery(hash, sig); } } contract ReconVerifyTest { function test_v0() public returns (bool) { bytes32 hash = 0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad; bytes memory sig = "\xac\xa7\xda\x99\x7a\xd1\x77\xf0\x40\x24\x0c\xdc\xcf\x69\x05\xb7\x1a\xb1\x6b\x74\x43\x43\x88\xc3\xa7\x2f\x34\xfd\x25\xd6\x43\x93\x46\xb2\xba\xc2\x74\xff\x29\xb4\x8b\x3e\xa6\xe2\xd0\x4c\x13\x36\xea\xce\xaf\xda\x3c\x53\xab\x48\x3f\xc3\xff\x12\xfa\xc3\xeb\xf2\x00"; return ReconVerify.verify(hash, sig, 0x0A5f85C3d41892C934ae82BDbF17027A20717088); } function test_v1() public returns (bool) { bytes32 hash = 0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad; bytes memory sig = "\xde\xba\xaa\x0c\xdd\xb3\x21\xb2\xdc\xaa\xf8\x46\xd3\x96\x05\xde\x7b\x97\xe7\x7b\xa6\x10\x65\x87\x85\x5b\x91\x06\xcb\x10\x42\x15\x61\xa2\x2d\x94\xfa\x8b\x8a\x68\x7f\xf9\xc9\x11\xc8\x44\xd1\xc0\x16\xd1\xa6\x85\xa9\x16\x68\x58\xf9\xc7\xc1\xbc\x85\x12\x8a\xca\x01"; return ReconVerify.verify(hash, sig, 0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract owned { address public owner; function ReconOwned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract tokenRecipient { event receivedEther(address sender, uint amount); event receivedTokens(address _from, uint256 _value, address _token, bytes _extraData); function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public { Token t = Token(_token); require(t.transferFrom(_from, this, _value)); emit receivedTokens(_from, _value, _token, _extraData); } function () payable public { emit receivedEther(msg.sender, msg.value); } } interface Token { function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); } contract Congress is owned, tokenRecipient { // Contract Variables and events uint public minimumQuorum; uint public debatingPeriodInMinutes; int public majorityMargin; Proposal[] public proposals; uint public numProposals; mapping (address => uint) public memberId; Member[] public members; event ProposalAdded(uint proposalID, address recipient, uint amount, string description); event Voted(uint proposalID, bool position, address voter, string justification); event ProposalTallied(uint proposalID, int result, uint quorum, bool active); event MembershipChanged(address member, bool isMember); event ChangeOfRules(uint newMinimumQuorum, uint newDebatingPeriodInMinutes, int newMajorityMargin); struct Proposal { address recipient; uint amount; string description; uint minExecutionDate; bool executed; bool proposalPassed; uint numberOfVotes; int currentResult; bytes32 proposalHash; Vote[] votes; mapping (address => bool) voted; } struct Member { address member; string name; uint memberSince; } struct Vote { bool inSupport; address voter; string justification; } // Modifier that allows only shareholders to vote and create new proposals modifier onlyMembers { require(memberId[msg.sender] != 0); _; } /** * Constructor function */ function ReconCongress ( uint minimumQuorumForProposals, uint minutesForDebate, int marginOfVotesForMajority ) payable public { changeVotingRules(minimumQuorumForProposals, minutesForDebate, marginOfVotesForMajority); // It’s necessary to add an empty first member addMember(0, ""); // and lets add the founder, to save a step later addMember(owner, 'founder'); } /** * Add member * * Make `targetMember` a member named `memberName` * * @param targetMember ethereum address to be added * @param memberName public name for that member */ function addMember(address targetMember, string memberName) onlyOwner public { uint id = memberId[targetMember]; if (id == 0) { memberId[targetMember] = members.length; id = members.length++; } members[id] = Member({member: targetMember, memberSince: now, name: memberName}); emit MembershipChanged(targetMember, true); } /** * Remove member * * @notice Remove membership from `targetMember` * * @param targetMember ethereum address to be removed */ function removeMember(address targetMember) onlyOwner public { require(memberId[targetMember] != 0); for (uint i = memberId[targetMember]; i<members.length-1; i++){ members[i] = members[i+1]; } delete members[members.length-1]; members.length--; } /** * Change voting rules * * Make so that proposals need to be discussed for at least `minutesForDebate/60` hours, * have at least `minimumQuorumForProposals` votes, and have 50% + `marginOfVotesForMajority` votes to be executed * * @param minimumQuorumForProposals how many members must vote on a proposal for it to be executed * @param minutesForDebate the minimum amount of delay between when a proposal is made and when it can be executed * @param marginOfVotesForMajority the proposal needs to have 50% plus this number */ function changeVotingRules( uint minimumQuorumForProposals, uint minutesForDebate, int marginOfVotesForMajority ) onlyOwner public { minimumQuorum = minimumQuorumForProposals; debatingPeriodInMinutes = minutesForDebate; majorityMargin = marginOfVotesForMajority; emit ChangeOfRules(minimumQuorum, debatingPeriodInMinutes, majorityMargin); } /** * Add Proposal * * Propose to send `weiAmount / 1e18` ether to `beneficiary` for `jobDescription`. `transactionBytecode ? Contains : Does not contain` code. * * @param beneficiary who to send the ether to * @param weiAmount amount of ether to send, in wei * @param jobDescription Description of job * @param transactionBytecode bytecode of transaction */ function newProposal( address beneficiary, uint weiAmount, string jobDescription, bytes transactionBytecode ) onlyMembers public returns (uint proposalID) { proposalID = proposals.length++; Proposal storage p = proposals[proposalID]; p.recipient = beneficiary; p.amount = weiAmount; p.description = jobDescription; p.proposalHash = keccak256(abi.encodePacked(beneficiary, weiAmount, transactionBytecode)); p.minExecutionDate = now + debatingPeriodInMinutes * 1 minutes; p.executed = false; p.proposalPassed = false; p.numberOfVotes = 0; emit ProposalAdded(proposalID, beneficiary, weiAmount, jobDescription); numProposals = proposalID+1; return proposalID; } /** * Add proposal in Ether * * Propose to send `etherAmount` ether to `beneficiary` for `jobDescription`. `transactionBytecode ? Contains : Does not contain` code. * This is a convenience function to use if the amount to be given is in round number of ether units. * * @param beneficiary who to send the ether to * @param etherAmount amount of ether to send * @param jobDescription Description of job * @param transactionBytecode bytecode of transaction */ function newProposalInEther( address beneficiary, uint etherAmount, string jobDescription, bytes transactionBytecode ) onlyMembers public returns (uint proposalID) { return newProposal(beneficiary, etherAmount * 1 ether, jobDescription, transactionBytecode); } /** * Check if a proposal code matches * * @param proposalNumber ID number of the proposal to query * @param beneficiary who to send the ether to * @param weiAmount amount of ether to send * @param transactionBytecode bytecode of transaction */ function checkProposalCode( uint proposalNumber, address beneficiary, uint weiAmount, bytes transactionBytecode ) constant public returns (bool codeChecksOut) { Proposal storage p = proposals[proposalNumber]; return p.proposalHash == keccak256(abi.encodePacked(beneficiary, weiAmount, transactionBytecode)); } /** * Log a vote for a proposal * * Vote `supportsProposal? in support of : against` proposal #`proposalNumber` * * @param proposalNumber number of proposal * @param supportsProposal either in favor or against it * @param justificationText optional justification text */ function vote( uint proposalNumber, bool supportsProposal, string justificationText ) onlyMembers public returns (uint voteID) { Proposal storage p = proposals[proposalNumber]; // Get the proposal require(!p.voted[msg.sender]); // If has already voted, cancel p.voted[msg.sender] = true; // Set this voter as having voted p.numberOfVotes++; // Increase the number of votes if (supportsProposal) { // If they support the proposal p.currentResult++; // Increase score } else { // If they dont p.currentResult--; // Decrease the score } // Create a log of this event emit Voted(proposalNumber, supportsProposal, msg.sender, justificationText); return p.numberOfVotes; } /** * Finish vote * * Count the votes proposal #`proposalNumber` and execute it if approved * * @param proposalNumber proposal number * @param transactionBytecode optional: if the transaction contained a bytecode, you need to send it */ function executeProposal(uint proposalNumber, bytes transactionBytecode) public { Proposal storage p = proposals[proposalNumber]; require(now > p.minExecutionDate // If it is past the voting deadline && !p.executed // and it has not already been executed && p.proposalHash == keccak256(abi.encodePacked(p.recipient, p.amount, transactionBytecode)) // and the supplied code matches the proposal && p.numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached... // ...then execute result if (p.currentResult > majorityMargin) { // Proposal passed; execute the transaction p.executed = true; // Avoid recursive calling require(p.recipient.call.value(p.amount)(transactionBytecode)); p.proposalPassed = true; } else { // Proposal failed p.proposalPassed = false; } // Fire Events emit ProposalTallied(proposalNumber, p.currentResult, p.numberOfVotes, p.proposalPassed); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } pragma solidity ^ 0.4.25; // ---------------------------------------------------------------------------- // Recon DateTime Library v1.00 // // A energy-efficient Solidity date and time library // // 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 // // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- library ReconDateTimeLibrary { 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) { 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 isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity ^ 0.4.25; // ---------------------------------------------------------------------------- // Recon DateTime Library v1.00 - Contract Instance // // A energy-efficient Solidity date and time library // // // 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 // // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- contract ReconDateTimeContract { uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant SECONDS_PER_HOUR = 60 * 60; uint public constant SECONDS_PER_MINUTE = 60; int public constant OFFSET19700101 = 2440588; uint public constant DOW_MON = 1; uint public constant DOW_TUE = 2; uint public constant DOW_WED = 3; uint public constant DOW_THU = 4; uint public constant DOW_FRI = 5; uint public constant DOW_SAT = 6; uint public constant DOW_SUN = 7; function _now() public view returns (uint timestamp) { timestamp = now; } function _nowDateTime() public view returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day, hour, minute, second) = ReconDateTimeLibrary.timestampToDateTime(now); } function _daysFromDate(uint year, uint month, uint day) public pure returns (uint _days) { return ReconDateTimeLibrary._daysFromDate(year, month, day); } function _daysToDate(uint _days) public pure returns (uint year, uint month, uint day) { return ReconDateTimeLibrary._daysToDate(_days); } function timestampFromDate(uint year, uint month, uint day) public pure returns (uint timestamp) { return ReconDateTimeLibrary.timestampFromDate(year, month, day); } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (uint timestamp) { return ReconDateTimeLibrary.timestampFromDateTime(year, month, day, hour, minute, second); } function timestampToDate(uint timestamp) public pure returns (uint year, uint month, uint day) { (year, month, day) = ReconDateTimeLibrary.timestampToDate(timestamp); } function timestampToDateTime(uint timestamp) public pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day, hour, minute, second) = ReconDateTimeLibrary.timestampToDateTime(timestamp); } function isLeapYear(uint timestamp) public pure returns (bool leapYear) { leapYear = ReconDateTimeLibrary.isLeapYear(timestamp); } function _isLeapYear(uint year) public pure returns (bool leapYear) { leapYear = ReconDateTimeLibrary._isLeapYear(year); } function isWeekDay(uint timestamp) public pure returns (bool weekDay) { weekDay = ReconDateTimeLibrary.isWeekDay(timestamp); } function isWeekEnd(uint timestamp) public pure returns (bool weekEnd) { weekEnd = ReconDateTimeLibrary.isWeekEnd(timestamp); } function getDaysInMonth(uint timestamp) public pure returns (uint daysInMonth) { daysInMonth = ReconDateTimeLibrary.getDaysInMonth(timestamp); } function _getDaysInMonth(uint year, uint month) public pure returns (uint daysInMonth) { daysInMonth = ReconDateTimeLibrary._getDaysInMonth(year, month); } function getDayOfWeek(uint timestamp) public pure returns (uint dayOfWeek) { dayOfWeek = ReconDateTimeLibrary.getDayOfWeek(timestamp); } function getYear(uint timestamp) public pure returns (uint year) { year = ReconDateTimeLibrary.getYear(timestamp); } function getMonth(uint timestamp) public pure returns (uint month) { month = ReconDateTimeLibrary.getMonth(timestamp); } function getDay(uint timestamp) public pure returns (uint day) { day = ReconDateTimeLibrary.getDay(timestamp); } function getHour(uint timestamp) public pure returns (uint hour) { hour = ReconDateTimeLibrary.getHour(timestamp); } function getMinute(uint timestamp) public pure returns (uint minute) { minute = ReconDateTimeLibrary.getMinute(timestamp); } function getSecond(uint timestamp) public pure returns (uint second) { second = ReconDateTimeLibrary.getSecond(timestamp); } function addYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addYears(timestamp, _years); } function addMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addMonths(timestamp, _months); } function addDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addDays(timestamp, _days); } function addHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addHours(timestamp, _hours); } function addMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addMinutes(timestamp, _minutes); } function addSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addSeconds(timestamp, _seconds); } function subYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subYears(timestamp, _years); } function subMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subMonths(timestamp, _months); } function subDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subDays(timestamp, _days); } function subHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subHours(timestamp, _hours); } function subMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subMinutes(timestamp, _minutes); } function subSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subSeconds(timestamp, _seconds); } function diffYears(uint fromTimestamp, uint toTimestamp) public pure returns (uint _years) { _years = ReconDateTimeLibrary.diffYears(fromTimestamp, toTimestamp); } function diffMonths(uint fromTimestamp, uint toTimestamp) public pure returns (uint _months) { _months = ReconDateTimeLibrary.diffMonths(fromTimestamp, toTimestamp); } function diffDays(uint fromTimestamp, uint toTimestamp) public pure returns (uint _days) { _days = ReconDateTimeLibrary.diffDays(fromTimestamp, toTimestamp); } function diffHours(uint fromTimestamp, uint toTimestamp) public pure returns (uint _hours) { _hours = ReconDateTimeLibrary.diffHours(fromTimestamp, toTimestamp); } function diffMinutes(uint fromTimestamp, uint toTimestamp) public pure returns (uint _minutes) { _minutes = ReconDateTimeLibrary.diffMinutes(fromTimestamp, toTimestamp); } function diffSeconds(uint fromTimestamp, uint toTimestamp) public pure returns (uint _seconds) { _seconds = ReconDateTimeLibrary.diffSeconds(fromTimestamp, toTimestamp); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes32 hash) public; } contract ReconTokenInterface is ERC20Interface { uint public constant reconVersion = 110; bytes public constant signingPrefix = "\x19Ethereum Signed Message:\n32"; bytes4 public constant signedTransferSig = "\x75\x32\xea\xac"; bytes4 public constant signedApproveSig = "\xe9\xaf\xa7\xa1"; bytes4 public constant signedTransferFromSig = "\x34\x4b\xcc\x7d"; bytes4 public constant signedApproveAndCallSig = "\xf1\x6f\x9b\x53"; event OwnershipTransferred(address indexed from, address indexed to); event MinterUpdated(address from, address to); event Mint(address indexed tokenOwner, uint tokens, bool lockAccount); event MintingDisabled(); event TransfersEnabled(); event AccountUnlocked(address indexed tokenOwner); function approveAndCall(address spender, uint tokens, bytes32 hash) public returns (bool success); // ------------------------------------------------------------------------ // signed{X} functions // ------------------------------------------------------------------------ function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (CheckResult result); function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success); function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (CheckResult result); function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success); function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (CheckResult result); function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success); function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce) public view returns (bytes32 hash); function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (CheckResult result); function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success); function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success); function unlockAccount(address tokenOwner) public; function disableMinting() public; function enableTransfers() public; enum CheckResult { Success, // 0 Success NotTransferable, // 1 Tokens not transferable yet AccountLocked, // 2 Account locked SignerMismatch, // 3 Mismatch in signing account InvalidNonce, // 4 Invalid nonce InsufficientApprovedTokens, // 5 Insufficient approved tokens InsufficientApprovedTokensForFees, // 6 Insufficient approved tokens for fees InsufficientTokens, // 7 Insufficient tokens InsufficientTokensForFees, // 8 Insufficient tokens for fees OverflowError // 9 Overflow error } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; library ReconLib { struct Data { bool initialised; // Ownership address owner; address newOwner; // Minting and management address minter; bool mintable; bool transferable; mapping(address => bool) accountLocked; // Token string symbol; string name; uint8 decimals; uint totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => uint) nextNonce; } uint public constant reconVersion = 110; bytes public constant signingPrefix = "\x19Ethereum Signed Message:\n32"; bytes4 public constant signedTransferSig = "\x75\x32\xea\xac"; bytes4 public constant signedApproveSig = "\xe9\xaf\xa7\xa1"; bytes4 public constant signedTransferFromSig = "\x34\x4b\xcc\x7d"; bytes4 public constant signedApproveAndCallSig = "\xf1\x6f\x9b\x53"; event OwnershipTransferred(address indexed from, address indexed to); event MinterUpdated(address from, address to); event Mint(address indexed tokenOwner, uint tokens, bool lockAccount); event MintingDisabled(); event TransfersEnabled(); event AccountUnlocked(address indexed tokenOwner); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); function init(Data storage self, address owner, string symbol, string name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public { require(!self.initialised); self.initialised = true; self.owner = owner; self.symbol = symbol; self.name = name; self.decimals = decimals; if (initialSupply > 0) { self.balances[owner] = initialSupply; self.totalSupply = initialSupply; emit Mint(self.owner, initialSupply, false); emit Transfer(address(0), self.owner, initialSupply); } self.mintable = mintable; self.transferable = transferable; } function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } function transferOwnership(Data storage self, address newOwner) public { require(msg.sender == self.owner); self.newOwner = newOwner; } function acceptOwnership(Data storage self) public { require(msg.sender == self.newOwner); emit OwnershipTransferred(self.owner, self.newOwner); self.owner = self.newOwner; self.newOwner = address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } function transferOwnershipImmediately(Data storage self, address newOwner) public { require(msg.sender == self.owner); emit OwnershipTransferred(self.owner, newOwner); self.owner = newOwner; self.newOwner = address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } // ------------------------------------------------------------------------ // Minting and management // ------------------------------------------------------------------------ function setMinter(Data storage self, address minter) public { require(msg.sender == self.owner); require(self.mintable); emit MinterUpdated(self.minter, minter); self.minter = minter; } function mint(Data storage self, address tokenOwner, uint tokens, bool lockAccount) public returns (bool success) { require(self.mintable); require(msg.sender == self.minter || msg.sender == self.owner); if (lockAccount) { self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = true; } self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeAdd(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], tokens); self.totalSupply = safeAdd(self.totalSupply, tokens); emit Mint(tokenOwner, tokens, lockAccount); emit Transfer(address(0x0A5f85C3d41892C934ae82BDbF17027A20717088), tokenOwner, tokens); return true; } function unlockAccount(Data storage self, address tokenOwner) public { require(msg.sender == self.owner); require(self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]); self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = false; emit AccountUnlocked(tokenOwner); } function disableMinting(Data storage self) public { require(self.mintable); require(msg.sender == self.minter || msg.sender == self.owner); self.mintable = false; if (self.minter != address(0x3Da2585FEbE344e52650d9174e7B1bf35C70D840)) { emit MinterUpdated(self.minter, address(0x3Da2585FEbE344e52650d9174e7B1bf35C70D840)); self.minter = address(0x3Da2585FEbE344e52650d9174e7B1bf35C70D840); } emit MintingDisabled(); } function enableTransfers(Data storage self) public { require(msg.sender == self.owner); require(!self.transferable); self.transferable = true; emit TransfersEnabled(); } // ------------------------------------------------------------------------ // Other functions // ------------------------------------------------------------------------ function transferAnyERC20Token(Data storage self, address tokenAddress, uint tokens) public returns (bool success) { require(msg.sender == self.owner); return ERC20Interface(tokenAddress).transfer(self.owner, tokens); } function ecrecoverFromSig(bytes32 hash, bytes32 sig) public pure returns (address recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return address(0x5f2D6766C6F3A7250CfD99d6b01380C432293F0c); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(32, mload(add(sig, 96))) } // Albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] // geth uses [0, 1] and some clients have followed. This might change, see https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) { v += 27; } if (v != 27 && v != 28) return address(0x5f2D6766C6F3A7250CfD99d6b01380C432293F0c); return ecrecover(hash, v, r, s); } function getCheckResultMessage(Data storage /*self*/, ReconTokenInterface.CheckResult result) public pure returns (string) { if (result == ReconTokenInterface.CheckResult.Success) { return "Success"; } else if (result == ReconTokenInterface.CheckResult.NotTransferable) { return "Tokens not transferable yet"; } else if (result == ReconTokenInterface.CheckResult.AccountLocked) { return "Account locked"; } else if (result == ReconTokenInterface.CheckResult.SignerMismatch) { return "Mismatch in signing account"; } else if (result == ReconTokenInterface.CheckResult.InvalidNonce) { return "Invalid nonce"; } else if (result == ReconTokenInterface.CheckResult.InsufficientApprovedTokens) { return "Insufficient approved tokens"; } else if (result == ReconTokenInterface.CheckResult.InsufficientApprovedTokensForFees) { return "Insufficient approved tokens for fees"; } else if (result == ReconTokenInterface.CheckResult.InsufficientTokens) { return "Insufficient tokens"; } else if (result == ReconTokenInterface.CheckResult.InsufficientTokensForFees) { return "Insufficient tokens for fees"; } else if (result == ReconTokenInterface.CheckResult.OverflowError) { return "Overflow error"; } else { return "Unknown error"; } } function transfer(Data storage self, address to, uint tokens) public returns (bool success) { // Owner and minter can move tokens before the tokens are transferable require(self.transferable || (self.mintable && (msg.sender == self.owner || msg.sender == self.minter))); require(!self.accountLocked[msg.sender]); self.balances[msg.sender] = safeSub(self.balances[msg.sender], tokens); self.balances[to] = safeAdd(self.balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(Data storage self, address spender, uint tokens) public returns (bool success) { require(!self.accountLocked[msg.sender]); self.allowed[msg.sender][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(Data storage self, address from, address to, uint tokens) public returns (bool success) { require(self.transferable); require(!self.accountLocked[from]); self.balances[from] = safeSub(self.balances[from], tokens); self.allowed[from][msg.sender] = safeSub(self.allowed[from][msg.sender], tokens); self.balances[to] = safeAdd(self.balances[to], tokens); emit Transfer(from, to, tokens); return true; } function approveAndCall(Data storage self, address spender, uint tokens, bytes32 data) public returns (bool success) { require(!self.accountLocked[msg.sender]); self.allowed[msg.sender][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function signedTransferHash(Data storage /*self*/, address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { hash = keccak256(abi.encodePacked(signedTransferSig, address(this), tokenOwner, to, tokens, fee, nonce)); } function signedTransferCheck(Data storage self, address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { if (!self.transferable) return ReconTokenInterface.CheckResult.NotTransferable; bytes32 hash = signedTransferHash(self, tokenOwner, to, tokens, fee, nonce); if (tokenOwner == address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) || tokenOwner != ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)) return ReconTokenInterface.CheckResult.SignerMismatch; if (self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]) return ReconTokenInterface.CheckResult.AccountLocked; if (self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] != nonce) return ReconTokenInterface.CheckResult.InvalidNonce; uint total = safeAdd(tokens, fee); if (self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] < tokens) return ReconTokenInterface.CheckResult.InsufficientTokens; if (self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] < total) return ReconTokenInterface.CheckResult.InsufficientTokensForFees; if (self.balances[to] + tokens < self.balances[to]) return ReconTokenInterface.CheckResult.OverflowError; if (self.balances[feeAccount] + fee < self.balances[feeAccount]) return ReconTokenInterface.CheckResult.OverflowError; return ReconTokenInterface.CheckResult.Success; } function signedTransfer(Data storage self, address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { require(self.transferable); bytes32 hash = signedTransferHash(self, tokenOwner, to, tokens, fee, nonce); require(tokenOwner != address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) && tokenOwner == ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)); require(!self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]); require(self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] == nonce); self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = nonce + 1; self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeSub(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], tokens); self.balances[to] = safeAdd(self.balances[to], tokens); emit Transfer(tokenOwner, to, tokens); self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeSub(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], fee); self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b] = safeAdd(self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b], fee); emit Transfer(tokenOwner, feeAccount, fee); return true; } function signedApproveHash(Data storage /*self*/, address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { hash = keccak256(abi.encodePacked(signedApproveSig, address(this), tokenOwner, spender, tokens, fee, nonce)); } function signedApproveCheck(Data storage self, address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { if (!self.transferable) return ReconTokenInterface.CheckResult.NotTransferable; bytes32 hash = signedApproveHash(self, tokenOwner, spender, tokens, fee, nonce); if (tokenOwner == address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) || tokenOwner != ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)) return ReconTokenInterface.CheckResult.SignerMismatch; if (self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]) return ReconTokenInterface.CheckResult.AccountLocked; if (self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] != nonce) return ReconTokenInterface.CheckResult.InvalidNonce; if (self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] < fee) return ReconTokenInterface.CheckResult.InsufficientTokensForFees; if (self.balances[feeAccount] + fee < self.balances[feeAccount]) return ReconTokenInterface.CheckResult.OverflowError; return ReconTokenInterface.CheckResult.Success; } function signedApprove(Data storage self, address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { require(self.transferable); bytes32 hash = signedApproveHash(self, tokenOwner, spender, tokens, fee, nonce); require(tokenOwner != address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) && tokenOwner == ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)); require(!self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]); require(self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] == nonce); self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = nonce + 1; self.allowed[0x0A5f85C3d41892C934ae82BDbF17027A20717088][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = tokens; emit Approval(0x0A5f85C3d41892C934ae82BDbF17027A20717088, spender, tokens); self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeSub(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], fee); self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b] = safeAdd(self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b], fee); emit Transfer(tokenOwner, feeAccount, fee); return true; } function signedTransferFromHash(Data storage /*self*/, address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { hash = keccak256(abi.encodePacked(signedTransferFromSig, address(this), spender, from, to, tokens, fee, nonce)); } function signedTransferFromCheck(Data storage self, address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { if (!self.transferable) return ReconTokenInterface.CheckResult.NotTransferable; bytes32 hash = signedTransferFromHash(self, spender, from, to, tokens, fee, nonce); if (spender == address(0xF848332f5D902EFD874099458Bc8A53C8b7881B1) || spender != ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)) return ReconTokenInterface.CheckResult.SignerMismatch; if (self.accountLocked[from]) return ReconTokenInterface.CheckResult.AccountLocked; if (self.nextNonce[spender] != nonce) return ReconTokenInterface.CheckResult.InvalidNonce; uint total = safeAdd(tokens, fee); if (self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] < tokens) return ReconTokenInterface.CheckResult.InsufficientApprovedTokens; if (self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] < total) return ReconTokenInterface.CheckResult.InsufficientApprovedTokensForFees; if (self.balances[from] < tokens) return ReconTokenInterface.CheckResult.InsufficientTokens; if (self.balances[from] < total) return ReconTokenInterface.CheckResult.InsufficientTokensForFees; if (self.balances[to] + tokens < self.balances[to]) return ReconTokenInterface.CheckResult.OverflowError; if (self.balances[feeAccount] + fee < self.balances[feeAccount]) return ReconTokenInterface.CheckResult.OverflowError; return ReconTokenInterface.CheckResult.Success; } function signedTransferFrom(Data storage self, address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { require(self.transferable); bytes32 hash = signedTransferFromHash(self, spender, from, to, tokens, fee, nonce); require(spender != address(0xF848332f5D902EFD874099458Bc8A53C8b7881B1) && spender == ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)); require(!self.accountLocked[from]); require(self.nextNonce[0xF848332f5D902EFD874099458Bc8A53C8b7881B1] == nonce); self.nextNonce[0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = nonce + 1; self.balances[from] = safeSub(self.balances[from], tokens); self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = safeSub(self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1], tokens); self.balances[to] = safeAdd(self.balances[to], tokens); emit Transfer(from, to, tokens); self.balances[from] = safeSub(self.balances[from], fee); self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = safeSub(self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1], fee); self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b] = safeAdd(self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b], fee); emit Transfer(from, feeAccount, fee); return true; } function signedApproveAndCallHash(Data storage /*self*/, address tokenOwner, address spender, uint tokens, bytes32 data, uint fee, uint nonce) public view returns (bytes32 hash) { hash = keccak256(abi.encodePacked(signedApproveAndCallSig, address(this), tokenOwner, spender, tokens, data, fee, nonce)); } function signedApproveAndCallCheck(Data storage self, address tokenOwner, address spender, uint tokens, bytes32 data, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { if (!self.transferable) return ReconTokenInterface.CheckResult.NotTransferable; bytes32 hash = signedApproveAndCallHash(self, tokenOwner, spender, tokens, data, fee, nonce); if (tokenOwner == address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) || tokenOwner != ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)) return ReconTokenInterface.CheckResult.SignerMismatch; if (self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]) return ReconTokenInterface.CheckResult.AccountLocked; if (self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] != nonce) return ReconTokenInterface.CheckResult.InvalidNonce; if (self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] < fee) return ReconTokenInterface.CheckResult.InsufficientTokensForFees; if (self.balances[feeAccount] + fee < self.balances[feeAccount]) return ReconTokenInterface.CheckResult.OverflowError; return ReconTokenInterface.CheckResult.Success; } function signedApproveAndCall(Data storage self, address tokenOwner, address spender, uint tokens, bytes32 data, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { require(self.transferable); bytes32 hash = signedApproveAndCallHash(self, tokenOwner, spender, tokens, data, fee, nonce); require(tokenOwner != address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) && tokenOwner == ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)); require(!self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]); require(self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] == nonce); self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = nonce + 1; self.allowed[0x0A5f85C3d41892C934ae82BDbF17027A20717088][spender] = tokens; emit Approval(tokenOwner, spender, tokens); self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeSub(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], fee); self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b] = safeAdd(self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b], fee); emit Transfer(tokenOwner, feeAccount, fee); ApproveAndCallFallBack(spender).receiveApproval(tokenOwner, tokens, address(this), data); return true; } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract ReconToken is ReconTokenInterface{ using ReconLib for ReconLib.Data; ReconLib.Data data; function constructorReconToken(address owner, string symbol, string name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public { data.init(owner, symbol, name, decimals, initialSupply, mintable, transferable); } function owner() public view returns (address) { return data.owner; } function newOwner() public view returns (address) { return data.newOwner; } function transferOwnership(address _newOwner) public { data.transferOwnership(_newOwner); } function acceptOwnership() public { data.acceptOwnership(); } function transferOwnershipImmediately(address _newOwner) public { data.transferOwnershipImmediately(_newOwner); } function symbol() public view returns (string) { return data.symbol; } function name() public view returns (string) { return data.name; } function decimals() public view returns (uint8) { return data.decimals; } function minter() public view returns (address) { return data.minter; } function setMinter(address _minter) public { data.setMinter(_minter); } function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success) { return data.mint(tokenOwner, tokens, lockAccount); } function accountLocked(address tokenOwner) public view returns (bool) { return data.accountLocked[tokenOwner]; } function unlockAccount(address tokenOwner) public { data.unlockAccount(tokenOwner); } function mintable() public view returns (bool) { return data.mintable; } function transferable() public view returns (bool) { return data.transferable; } function disableMinting() public { data.disableMinting(); } function enableTransfers() public { data.enableTransfers(); } function nextNonce(address spender) public view returns (uint) { return data.nextNonce[spender]; } // ------------------------------------------------------------------------ // Other functions // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) { return data.transferAnyERC20Token(tokenAddress, tokens); } function () public payable { revert(); } function totalSupply() public view returns (uint) { return data.totalSupply - data.balances[address(0x0A5f85C3d41892C934ae82BDbF17027A20717088)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return data.balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return data.allowed[tokenOwner][spender]; } function transfer(address to, uint tokens) public returns (bool success) { return data.transfer(to, tokens); } function approve(address spender, uint tokens) public returns (bool success) { return data.approve(spender, tokens); } function transferFrom(address from, address to, uint tokens) public returns (bool success) { return data.transferFrom(from, to, tokens); } function approveAndCall(address spender, uint tokens, bytes32 _data) public returns (bool success) { return data.approveAndCall(spender, tokens, _data); } function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedTransferHash(tokenOwner, to, tokens, fee, nonce); } function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { return data.signedTransferCheck(tokenOwner, to, tokens, fee, nonce, sig, feeAccount); } function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { return data.signedTransfer(tokenOwner, to, tokens, fee, nonce, sig, feeAccount); } function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedApproveHash(tokenOwner, spender, tokens, fee, nonce); } function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { return data.signedApproveCheck(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount); } function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { return data.signedApprove(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount); } function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedTransferFromHash(spender, from, to, tokens, fee, nonce); } function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { return data.signedTransferFromCheck(spender, from, to, tokens, fee, nonce, sig, feeAccount); } function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { return data.signedTransferFrom(spender, from, to, tokens, fee, nonce, sig, feeAccount); } function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedApproveAndCallHash(tokenOwner, spender, tokens, _data, fee, nonce); } function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { return data.signedApproveAndCallCheck(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount); } function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { return data.signedApproveAndCall(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Owned1() public { owner = msg.sender; } constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(newOwner != address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060)); emit OwnershipTransferred(owner, newOwner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } function transferOwnershipImmediately(address _newOwner) public onlyOwner { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; newOwner = address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract ReconTokenFactory is ERC20Interface, Owned { using SafeMath for uint; string public constant name = "RECON"; string public constant symbol = "RECON"; uint8 public constant decimals = 18; uint constant public ReconToMicro = uint(1000000000000000000); // This constants reflects RECON token distribution uint constant public investorSupply = 25000000000 * ReconToMicro; uint constant public adviserSupply = 25000000 * ReconToMicro; uint constant public bountySupply = 25000000 * ReconToMicro; uint constant public _totalSupply = 100000000000 * ReconToMicro; uint constant public preICOSupply = 5000000000 * ReconToMicro; uint constant public presaleSupply = 5000000000 * ReconToMicro; uint constant public crowdsaleSupply = 10000000000 * ReconToMicro; uint constant public preICOprivate = 99000000 * ReconToMicro; uint constant public Reconowner = 101000000 * ReconToMicro; uint constant public ReconnewOwner = 100000000 * ReconToMicro; uint constant public Reconminter = 50000000 * ReconToMicro; uint constant public ReconfeeAccount = 50000000 * ReconToMicro; uint constant public Reconspender = 50000000 * ReconToMicro; uint constant public ReconrecoveredAddress = 50000000 * ReconToMicro; uint constant public ProprityfromReconBank = 200000000 * ReconToMicro; uint constant public ReconManager = 200000000 * ReconToMicro; uint constant public ReconCashinB2B = 5000000000 * ReconToMicro; uint constant public ReconSwitchC2C = 5000000000 * ReconToMicro; uint constant public ReconCashoutB2C = 5000000000 * ReconToMicro; uint constant public ReconInvestment = 2000000000 * ReconToMicro; uint constant public ReconMomentum = 2000000000 * ReconToMicro; uint constant public ReconReward = 2000000000 * ReconToMicro; uint constant public ReconDonate = 1000000000 * ReconToMicro; uint constant public ReconTokens = 4000000000 * ReconToMicro; uint constant public ReconCash = 4000000000 * ReconToMicro; uint constant public ReconGold = 4000000000 * ReconToMicro; uint constant public ReconCard = 4000000000 * ReconToMicro; uint constant public ReconHardriveWallet = 2000000000 * ReconToMicro; uint constant public RecoinOption = 1000000000 * ReconToMicro; uint constant public ReconPromo = 100000000 * ReconToMicro; uint constant public Reconpatents = 1000000000 * ReconToMicro; uint constant public ReconSecurityandLegalFees = 1000000000 * ReconToMicro; uint constant public PeerToPeerNetworkingService = 1000000000 * ReconToMicro; uint constant public Reconia = 2000000000 * ReconToMicro; uint constant public ReconVaultXtraStock = 7000000000 * ReconToMicro; uint constant public ReconVaultSecurityStock = 5000000000 * ReconToMicro; uint constant public ReconVaultAdvancePaymentStock = 5000000000 * ReconToMicro; uint constant public ReconVaultPrivatStock = 4000000000 * ReconToMicro; uint constant public ReconVaultCurrencyInsurancestock = 4000000000 * ReconToMicro; uint constant public ReconVaultNextStock = 4000000000 * ReconToMicro; uint constant public ReconVaultFuturStock = 4000000000 * ReconToMicro; // This variables accumulate amount of sold RECON during // presale, crowdsale, or given to investors as bonus. uint public presaleSold = 0; uint public crowdsaleSold = 0; uint public investorGiven = 0; // Amount of ETH received during ICO uint public ethSold = 0; uint constant public softcapUSD = 20000000000; uint constant public preicoUSD = 5000000000; // Presale lower bound in dollars. uint constant public crowdsaleMinUSD = ReconToMicro * 10 * 100 / 12; uint constant public bonusLevel0 = ReconToMicro * 10000 * 100 / 12; // 10000$ uint constant public bonusLevel100 = ReconToMicro * 100000 * 100 / 12; // 100000$ // The tokens made available to the public will be in 13 steps // for a maximum of 20% of the total supply (see doc for checkTransfer). // All dates are stored as timestamps. uint constant public unlockDate1 = 1541890800; // 11-11-2018 00:00:00 [1%] Recon Manager uint constant public unlockDate2 = 1545346800; // 21-12-2018 00:00:00 [2%] Recon Cash-in (B2B) uint constant public unlockDate3 = 1549062000; // 02-02-2019 00:00:00 [2%] Recon Switch (C2C) uint constant public unlockDate4 = 1554328800; // 04-04-2019 00:00:00 [2%] Recon Cash-out (B2C) uint constant public unlockDate5 = 1565215200; // 08-08-2019 00:00:00 [2%] Recon Investment & Recon Momentum uint constant public unlockDate6 = 1570658400; // 10-10-2019 00:00:00 [2%] Recon Reward uint constant public unlockDate7 = 1576105200; // 12-12-2019 00:00:00 [1%] Recon Donate uint constant public unlockDate8 = 1580598000; // 02-02-2020 00:00:00 [1%] Recon Token uint constant public unlockDate9 = 1585951200; // 04-04-2020 00:00:00 [2%] Recon Cash uint constant public unlockDate10 = 1591394400; // 06-06-2020 00:00:00 [1%] Recon Gold uint constant public unlockDate11 = 1596837600; // 08-08-2020 00:00:00 [2%] Recon Card uint constant public unlockDate12 = 1602280800; // 10-10-2020 00:00:00 [1%] Recon Hardrive Wallet uint constant public unlockDate13 = 1606863600; // 02-12-2020 00:00:00 [1%] Recoin Option // The tokens made available to the teams will be made in 4 steps // for a maximum of 80% of the total supply (see doc for checkTransfer). uint constant public teamUnlock1 = 1544569200; // 12-12-2018 00:00:00 [25%] uint constant public teamUnlock2 = 1576105200; // 12-12-2019 00:00:00 [25%] uint constant public teamUnlock3 = 1594072800; // 07-07-2020 00:00:00 [25%] uint constant public teamUnlock4 = 1608505200; // 21-12-2020 00:00:00 [25%] uint constant public teamETHUnlock1 = 1544569200; // 12-12-2018 00:00:00 uint constant public teamETHUnlock2 = 1576105200; // 12-12-2019 00:00:00 uint constant public teamETHUnlock3 = 1594072800; // 07-07-2020 00:00:00 //https://casperproject.atlassian.net/wiki/spaces/PROD/pages/277839878/Smart+contract+ICO // Presale 10.06.2018 - 22.07.2018 // Crowd-sale 23.07.2018 - 2.08.2018 (16.08.2018) uint constant public presaleStartTime = 1541890800; // 11-11-2018 00:00:00 uint constant public crowdsaleStartTime = 1545346800; // 21-12-2018 00:00:00 uint public crowdsaleEndTime = 1609455599; // 31-12-2020 23:59:59 uint constant public crowdsaleHardEndTime = 1609455599; // 31-12-2020 23:59:59 //address constant ReconrWallet = 0x0A5f85C3d41892C934ae82BDbF17027A20717088; constructor() public { admin = owner; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } modifier onlyAdmin { require(msg.sender == admin); _; } modifier onlyOwnerAndDirector { require(msg.sender == owner || msg.sender == director); _; } address admin; function setAdmin(address _newAdmin) public onlyOwnerAndDirector { admin = _newAdmin; } address director; function setDirector(address _newDirector) public onlyOwner { director = _newDirector; } bool assignedPreico = false; // @notice assignPreicoTokens transfers 3x tokens to pre-ICO participants (99,000,000) function assignPreicoTokens() public onlyOwnerAndDirector { require(!assignedPreico); assignedPreico = true; _freezeTransfer(0x4Bdff2Cc40996C71a1F16b72490d1a8E7Dfb7E56, 3 * 1000000000000000000000000); // Account_34 _freezeTransfer(0x9189AC4FA7AdBC587fF76DD43248520F8Cb897f3, 3 * 1000000000000000000000000); // Account_35 _freezeTransfer(0xc1D3DAd07A0dB42a7d34453C7d09eFeA793784e7, 3 * 1000000000000000000000000); // Account_36 _freezeTransfer(0xA0BC1BAAa5318E39BfB66F8Cd0496d6b09CaE6C1, 3 * 1000000000000000000000000); // Account_37 _freezeTransfer(0x9a2912F145Ab0d5b4aE6917A8b8ddd222539F424, 3 * 1000000000000000000000000); // Account_38 _freezeTransfer(0x0bB0ded1d868F1c0a50bD31c1ab5ab7b53c6BC20, 3 * 1000000000000000000000000); // Account_39 _freezeTransfer(0x65ec9f30249065A1BD23a9c68c0Ee9Ead63b4A4d, 3 * 1000000000000000000000000); // Account_40 _freezeTransfer(0x87Bdc03582deEeB84E00d3fcFd083B64DA77F471, 3 * 1000000000000000000000000); // Account_41 _freezeTransfer(0x81382A0998191E2Dd8a7bB2B8875D4Ff6CAA31ff, 3 * 1000000000000000000000000); // Account_42 _freezeTransfer(0x790069C894ebf518fB213F35b48C8ec5AAF81E62, 3 * 1000000000000000000000000); // Account_43 _freezeTransfer(0xa3f1404851E8156DFb425eC0EB3D3d5ADF6c8Fc0, 3 * 1000000000000000000000000); // Account_44 _freezeTransfer(0x11bA01dc4d93234D24681e1B19839D4560D17165, 3 * 1000000000000000000000000); // Account_45 _freezeTransfer(0x211D495291534009B8D3fa491400aB66F1d6131b, 3 * 1000000000000000000000000); // Account_46 _freezeTransfer(0x8c481AaF9a735F9a44Ac2ACFCFc3dE2e9B2f88f8, 3 * 1000000000000000000000000); // Account_47 _freezeTransfer(0xd0BEF2Fb95193f429f0075e442938F5d829a33c8, 3 * 1000000000000000000000000); // Account_48 _freezeTransfer(0x424cbEb619974ee79CaeBf6E9081347e64766705, 3 * 1000000000000000000000000); // Account_49 _freezeTransfer(0x9e395cd98089F6589b90643Dde4a304cAe4dA61C, 3 * 1000000000000000000000000); // Account_50 _freezeTransfer(0x3cDE6Df0906157107491ED17C79fF9218A50D7Dc, 3 * 1000000000000000000000000); // Account_51 _freezeTransfer(0x419a98D46a368A1704278349803683abB2A9D78E, 3 * 1000000000000000000000000); // Account_52 _freezeTransfer(0x106Db742344FBB96B46989417C151B781D1a4069, 3 * 1000000000000000000000000); // Account_53 _freezeTransfer(0xE16b9E9De165DbecA18B657414136cF007458aF5, 3 * 1000000000000000000000000); // Account_54 _freezeTransfer(0xee32C325A3E11759b290df213E83a257ff249936, 3 * 1000000000000000000000000); // Account_55 _freezeTransfer(0x7d6F916b0E5BF7Ba7f11E60ed9c30fB71C4A5fE0, 3 * 1000000000000000000000000); // Account_56 _freezeTransfer(0xCC684085585419100AE5010770557d5ad3F3CE58, 3 * 1000000000000000000000000); // Account_57 _freezeTransfer(0xB47BE6d74C5bC66b53230D07fA62Fb888594418d, 3 * 1000000000000000000000000); // Account_58 _freezeTransfer(0xf891555a1BF2525f6EBaC9b922b6118ca4215fdD, 3 * 1000000000000000000000000); // Account_59 _freezeTransfer(0xE3124478A5ed8550eA85733a4543Dd128461b668, 3 * 1000000000000000000000000); // Account_60 _freezeTransfer(0xc5836df630225112493fa04fa32B586f072d6298, 3 * 1000000000000000000000000); // Account_61 _freezeTransfer(0x144a0543C93ce8Fb26c13EB619D7E934FA3eA734, 3 * 1000000000000000000000000); // Account_62 _freezeTransfer(0x43731e24108E928984DcC63DE7affdF3a805FFb0, 3 * 1000000000000000000000000); // Account_63 _freezeTransfer(0x49f7744Aa8B706Faf336a3ff4De37078714065BC, 3 * 1000000000000000000000000); // Account_64 _freezeTransfer(0x1E55C7E97F0b5c162FC9C42Ced92C8e55053e093, 3 * 1000000000000000000000000); // Account_65 _freezeTransfer(0x40b234009664590997D2F6Fde2f279fE56e8AaBC, 3 * 1000000000000000000000000); // Account_66 } bool assignedTeam = false; // @notice assignTeamTokens assigns tokens to team members (79,901,000,000) // @notice tokens for team have their own supply function assignTeamTokens() public onlyOwnerAndDirector { require(!assignedTeam); assignedTeam = true; _teamTransfer(0x0A5f85C3d41892C934ae82BDbF17027A20717088, 101000000 * ReconToMicro); // Recon owner _teamTransfer(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060, 100000000 * ReconToMicro); // Recon newOwner _teamTransfer(0x3Da2585FEbE344e52650d9174e7B1bf35C70D840, 50000000 * ReconToMicro); // Recon minter _teamTransfer(0xc083E68D962c2E062D2735B54804Bb5E1f367c1b, 50000000 * ReconToMicro); // Recon feeAccount _teamTransfer(0xF848332f5D902EFD874099458Bc8A53C8b7881B1, 50000000 * ReconToMicro); // Recon spender _teamTransfer(0x5f2D6766C6F3A7250CfD99d6b01380C432293F0c, 50000000 * ReconToMicro); // Recon recoveredAddress _teamTransfer(0x5f2D6766C6F3A7250CfD99d6b01380C432293F0c, 200000000 * ReconToMicro); // Proprity from ReconBank _teamTransfer(0xD974C2D74f0F352467ae2Da87fCc64491117e7ac, 200000000 * ReconToMicro); // Recon Manager _teamTransfer(0x5c4F791D0E0A2E75Ee34D62c16FB6D09328555fF, 5000000000 * ReconToMicro); // Recon Cash-in (B2B) _teamTransfer(0xeB479640A6D55374aF36896eCe6db7d92F390015, 5000000000 * ReconToMicro); // Recon Switch (C2C) _teamTransfer(0x77167D25Db87dc072399df433e450B00b8Ec105A, 7000000000 * ReconToMicro); // Recon Cash-out (B2C) _teamTransfer(0x5C6Fd84b961Cce03e027B0f8aE23c4A6e1195E90, 2000000000 * ReconToMicro); // Recon Investment _teamTransfer(0x86F427c5e05C29Fd4124746f6111c1a712C9B5c8, 2000000000 * ReconToMicro); // Recon Momentum _teamTransfer(0x1Ecb8dC0932AF3A3ba87e8bFE7eac3Cbe433B78B, 2000000000 * ReconToMicro); // Recon Reward _teamTransfer(0x7C31BeCa0290C35c8452b95eA462C988c4003Bb0, 1000000000 * ReconToMicro); // Recon Donate _teamTransfer(0x3a5326f9C9b3ff99e2e5011Aabec7b48B2e6A6A2, 4000000000 * ReconToMicro); // Recon Token _teamTransfer(0x5a27B07003ce50A80dbBc5512eA5BBd654790673, 4000000000 * ReconToMicro); // Recon Cash _teamTransfer(0xD580cF1002d0B4eF7d65dC9aC6a008230cE22692, 4000000000 * ReconToMicro); // Recon Gold _teamTransfer(0x9C83562Bf58083ab408E596A4bA4951a2b5724C9, 4000000000 * ReconToMicro); // Recon Card _teamTransfer(0x70E06c2Dd9568ECBae760CE2B61aC221C0c497F5, 2000000000 * ReconToMicro); // Recon Hardrive Wallet _teamTransfer(0x14bd2Aa04619658F517521adba7E5A17dfD2A3f0, 1000000000 * ReconToMicro); // Recoin Option _teamTransfer(0x9C3091a335383566d08cba374157Bdff5b8B034B, 100000000 * ReconToMicro); // Recon Promo _teamTransfer(0x3b6F53122903c40ef61441dB807f09D90D6F05c7, 1000000000 * ReconToMicro); // Recon patents _teamTransfer(0x7fb5EF151446Adb0B7D39B1902E45f06E11038F6, 1000000000 * ReconToMicro); // Recon Security & Legal Fees _teamTransfer(0x47BD87fa63Ce818584F050aFFECca0f1dfFd0564, 1000000000 * ReconToMicro); // ​Peer To Peer Networking Service _teamTransfer(0x83b3CD589Bd78aE65d7b338fF7DFc835cD9a8edD, 2000000000 * ReconToMicro); // Reconia _teamTransfer(0x6299496342fFd22B7191616fcD19CeC6537C2E8D, 8000000000 * ReconToMicro); // ​Recon Central Securities Depository (Recon Vault XtraStock) _teamTransfer(0x26aF11607Fad4FacF1fc44271aFA63Dbf2C22a87, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault SecurityStock) _teamTransfer(0x7E21203C5B4A6f98E4986f850dc37eBE9Ca19179, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault Advance Payment Stock) _teamTransfer(0x0bD212e88522b7F4C673fccBCc38558829337f71, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault PrivatStock) _teamTransfer(0x5b44e309408cE6E73B9f5869C9eeaCeeb8084DC8, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault Currency Insurance stock) _teamTransfer(0x48F2eFDE1c028792EbE7a870c55A860e40eb3573, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault NextStock) _teamTransfer(0x1fF3BE6f711C684F04Cf6adfD665Ce13D54CAC73, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault FuturStock) } // @nptice kycPassed is executed by backend and tells SC // that particular client has passed KYC mapping(address => bool) public kyc; mapping(address => address) public referral; function kycPassed(address _mem, address _ref) public onlyAdmin { kyc[_mem] = true; if (_ref == richardAddr || _ref == wuguAddr) { referral[_mem] = _ref; } } // mappings for implementing ERC20 mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // mapping for implementing unlock mechanic mapping(address => uint) freezed; mapping(address => uint) teamFreezed; // ERC20 standard functions function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function _transfer(address _from, address _to, uint _tokens) private { balances[_from] = balances[_from].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(_from, _to, _tokens); } function transfer(address _to, uint _tokens) public returns (bool success) { checkTransfer(msg.sender, _tokens); _transfer(msg.sender, _to, _tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { checkTransfer(from, tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); _transfer(from, to, tokens); return true; } // @notice checkTransfer ensures that `from` can send only unlocked tokens // @notice this function is called for every transfer // We unlock PURCHASED and BONUS tokens in 13 stages: function checkTransfer(address from, uint tokens) public view { uint newBalance = balances[from].sub(tokens); uint total = 0; if (now < unlockDate5) { require(now >= unlockDate1); uint frzdPercent = 0; if (now < unlockDate2) { frzdPercent = 5; } else if (now < unlockDate3) { frzdPercent = 10; } else if (now < unlockDate4) { frzdPercent = 10; } else if (now < unlockDate5) { frzdPercent = 10; } else if (now < unlockDate6) { frzdPercent = 10; } else if (now < unlockDate7) { frzdPercent = 10; } else if (now < unlockDate8) { frzdPercent = 5; } else if (now < unlockDate9) { frzdPercent = 5; } else if (now < unlockDate10) { frzdPercent = 10; } else if (now < unlockDate11) { frzdPercent = 5; } else if (now < unlockDate12) { frzdPercent = 10; } else if (now < unlockDate13) { frzdPercent = 5; } else { frzdPercent = 5; } total = freezed[from].mul(frzdPercent).div(100); require(newBalance >= total); } if (now < teamUnlock4 && teamFreezed[from] > 0) { uint p = 0; if (now < teamUnlock1) { p = 100; } else if (now < teamUnlock2) { p = 75; } else if (now < teamUnlock3) { p = 50; } else if (now < teamUnlock4) { p = 25; } total = total.add(teamFreezed[from].mul(p).div(100)); require(newBalance >= total); } } // @return ($ received, ETH received, RECON sold) function ICOStatus() public view returns (uint usd, uint eth, uint recon) { usd = presaleSold.mul(12).div(10**20) + crowdsaleSold.mul(16).div(10**20); usd = usd.add(preicoUSD); // pre-ico tokens return (usd, ethSold + preicoUSD.mul(10**8).div(ethRate), presaleSold + crowdsaleSold); } function checkICOStatus() public view returns(bool) { uint eth; uint recon; (, eth, recon) = ICOStatus(); uint dollarsRecvd = eth.mul(ethRate).div(10**8); // 26 228 800$ return dollarsRecvd >= 25228966 || (recon == presaleSupply + crowdsaleSupply) || now > crowdsaleEndTime; } bool icoClosed = false; function closeICO() public onlyOwner { require(!icoClosed); icoClosed = checkICOStatus(); } // @notice by agreement, we can transfer $4.8M from bank // after softcap is reached. // @param _to wallet to send RECON to // @param _usd amount of dollars which is withdrawn uint bonusTransferred = 0; uint constant maxUSD = 4800000; function transferBonus(address _to, uint _usd) public onlyOwner { bonusTransferred = bonusTransferred.add(_usd); require(bonusTransferred <= maxUSD); uint recon = _usd.mul(100).mul(ReconToMicro).div(12); // presale tariff presaleSold = presaleSold.add(recon); require(presaleSold <= presaleSupply); ethSold = ethSold.add(_usd.mul(10**8).div(ethRate)); _freezeTransfer(_to, recon); } // @notice extend crowdsale for 2 weeks function prolongCrowdsale() public onlyOwnerAndDirector { require(now < crowdsaleEndTime); crowdsaleEndTime = crowdsaleHardEndTime; } // 100 000 000 Ether in dollars uint public ethRate = 0; uint public ethRateMax = 0; uint public ethLastUpdate = 0; function setETHRate(uint _rate) public onlyAdmin { require(ethRateMax == 0 || _rate < ethRateMax); ethRate = _rate; ethLastUpdate = now; } // 100 000 000 BTC in dollars uint public btcRate = 0; uint public btcRateMax = 0; uint public btcLastUpdate; function setBTCRate(uint _rate) public onlyAdmin { require(btcRateMax == 0 || _rate < btcRateMax); btcRate = _rate; btcLastUpdate = now; } // @notice setMaxRate sets max rate for both BTC/ETH to soften // negative consequences in case our backend gots hacked. function setMaxRate(uint ethMax, uint btcMax) public onlyOwnerAndDirector { ethRateMax = ethMax; btcRateMax = btcMax; } // @notice _sellPresale checks RECON purchases during crowdsale function _sellPresale(uint recon) private { require(recon >= bonusLevel0.mul(9950).div(10000)); presaleSold = presaleSold.add(recon); require(presaleSold <= presaleSupply); } // @notice _sellCrowd checks RECON purchases during crowdsale function _sellCrowd(uint recon, address _to) private { require(recon >= crowdsaleMinUSD); if (crowdsaleSold.add(recon) <= crowdsaleSupply) { crowdsaleSold = crowdsaleSold.add(recon); } else { presaleSold = presaleSold.add(crowdsaleSold).add(recon).sub(crowdsaleSupply); require(presaleSold <= presaleSupply); crowdsaleSold = crowdsaleSupply; } if (now < crowdsaleStartTime + 3 days) { if (whitemap[_to] >= recon) { whitemap[_to] -= recon; whitelistTokens -= recon; } else { require(crowdsaleSupply.add(presaleSupply).sub(presaleSold) >= crowdsaleSold.add(whitelistTokens)); } } } // @notice addInvestorBonusInPercent is used for sending bonuses for big investors in % function addInvestorBonusInPercent(address _to, uint8 p) public onlyOwner { require(p > 0 && p <= 5); uint bonus = balances[_to].mul(p).div(100); investorGiven = investorGiven.add(bonus); require(investorGiven <= investorSupply); _freezeTransfer(_to, bonus); } // @notice addInvestorBonusInTokens is used for sending bonuses for big investors in tokens function addInvestorBonusInTokens(address _to, uint tokens) public onlyOwner { _freezeTransfer(_to, tokens); investorGiven = investorGiven.add(tokens); require(investorGiven <= investorSupply); } function () payable public { purchaseWithETH(msg.sender); } // @notice _freezeTranfer perform actual tokens transfer which // will be freezed (see also checkTransfer() ) function _freezeTransfer(address _to, uint recon) private { _transfer(owner, _to, recon); freezed[_to] = freezed[_to].add(recon); } // @notice _freezeTranfer perform actual tokens transfer which // will be freezed (see also checkTransfer() ) function _teamTransfer(address _to, uint recon) private { _transfer(owner, _to, recon); teamFreezed[_to] = teamFreezed[_to].add(recon); } address public constant wuguAddr = 0x0d340F1344a262c13485e419860cb6c4d8Ec9C6e; address public constant richardAddr = 0x49BE16e7FECb14B82b4f661D9a0426F810ED7127; mapping(address => address[]) promoterClients; mapping(address => mapping(address => uint)) promoterBonus; // @notice withdrawPromoter transfers back to promoter // all bonuses accumulated to current moment function withdrawPromoter() public { address _to = msg.sender; require(_to == wuguAddr || _to == richardAddr); uint usd; (usd,,) = ICOStatus(); // USD received - 5% must be more than softcap require(usd.mul(95).div(100) >= softcapUSD); uint bonus = 0; address[] memory clients = promoterClients[_to]; for(uint i = 0; i < clients.length; i++) { if (kyc[clients[i]]) { uint num = promoterBonus[_to][clients[i]]; delete promoterBonus[_to][clients[i]]; bonus += num; } } _to.transfer(bonus); } // @notice cashBack will be used in case of failed ICO // All partitipants can receive their ETH back function cashBack(address _to) public { uint usd; (usd,,) = ICOStatus(); // ICO fails if crowd-sale is ended and we have not yet reached soft-cap require(now > crowdsaleEndTime && usd < softcapUSD); require(ethSent[_to] > 0); delete ethSent[_to]; _to.transfer(ethSent[_to]); } // @notice stores amount of ETH received by SC mapping(address => uint) ethSent; function purchaseWithETH(address _to) payable public { purchaseWithPromoter(_to, referral[msg.sender]); } // @notice purchases tokens, which a send to `_to` with 5% returned to `_ref` // @notice 5% return must work only on crowdsale function purchaseWithPromoter(address _to, address _ref) payable public { require(now >= presaleStartTime && now <= crowdsaleEndTime); require(!icoClosed); uint _wei = msg.value; uint recon; ethSent[msg.sender] = ethSent[msg.sender].add(_wei); ethSold = ethSold.add(_wei); // accept payment on presale only if it is more than 9997$ // actual check is performed in _sellPresale if (now < crowdsaleStartTime || approvedInvestors[msg.sender]) { require(kyc[msg.sender]); recon = _wei.mul(ethRate).div(75000000); // 1 RECON = 0.75 $ on presale require(now < crowdsaleStartTime || recon >= bonusLevel100); _sellPresale(recon); // we have only 2 recognized promoters if (_ref == wuguAddr || _ref == richardAddr) { promoterClients[_ref].push(_to); promoterBonus[_ref][_to] = _wei.mul(5).div(100); } } else { recon = _wei.mul(ethRate).div(10000000); // 1 RECON = 1.00 $ on crowd-sale _sellCrowd(recon, _to); } _freezeTransfer(_to, recon); } // @notice purchaseWithBTC is called from backend, where we convert // BTC to ETH, and then assign tokens to purchaser, using BTC / $ exchange rate. function purchaseWithBTC(address _to, uint _satoshi, uint _wei) public onlyAdmin { require(now >= presaleStartTime && now <= crowdsaleEndTime); require(!icoClosed); ethSold = ethSold.add(_wei); uint recon; // accept payment on presale only if it is more than 9997$ // actual check is performed in _sellPresale if (now < crowdsaleStartTime || approvedInvestors[msg.sender]) { require(kyc[msg.sender]); recon = _satoshi.mul(btcRate.mul(10000)).div(75); // 1 RECON = 0.75 $ on presale require(now < crowdsaleStartTime || recon >= bonusLevel100); _sellPresale(recon); } else { recon = _satoshi.mul(btcRate.mul(10000)).div(100); // 1 RECON = 1.00 $ on presale _sellCrowd(recon, _to); } _freezeTransfer(_to, recon); } // @notice withdrawFunds is called to send team bonuses after // then end of the ICO bool withdrawCalled = false; function withdrawFunds() public onlyOwner { require(icoClosed && now >= teamETHUnlock1); require(!withdrawCalled); withdrawCalled = true; uint eth; (,eth,) = ICOStatus(); // pre-ico tokens are not in ethSold uint minus = bonusTransferred.mul(10**8).div(ethRate); uint team = ethSold.sub(minus); team = team.mul(15).div(100); uint ownerETH = 0; uint teamETH = 0; if (address(this).balance >= team) { teamETH = team; ownerETH = address(this).balance.sub(teamETH); } else { teamETH = address(this).balance; } teamETH1 = teamETH.div(3); teamETH2 = teamETH.div(3); teamETH3 = teamETH.sub(teamETH1).sub(teamETH2); // TODO multisig address(0xf14B65F1589B8bC085578BcF68f09653D8F6abA8).transfer(ownerETH); } uint teamETH1 = 0; uint teamETH2 = 0; uint teamETH3 = 0; function withdrawTeam() public { require(now >= teamETHUnlock1); uint amount = 0; if (now < teamETHUnlock2) { amount = teamETH1; teamETH1 = 0; } else if (now < teamETHUnlock3) { amount = teamETH1 + teamETH2; teamETH1 = 0; teamETH2 = 0; } else { amount = teamETH1 + teamETH2 + teamETH3; teamETH1 = 0; teamETH2 = 0; teamETH3 = 0; } address(0x5c4F791D0E0A2E75Ee34D62c16FB6D09328555fF).transfer(amount.mul(6).div(100)); // Recon Cash-in (B2B) address(0xeB479640A6D55374aF36896eCe6db7d92F390015).transfer(amount.mul(6).div(100)); // Recon Switch (C2C) address(0x77167D25Db87dc072399df433e450B00b8Ec105A).transfer(amount.mul(6).div(100)); // Recon Cash-out (B2C) address(0x1Ecb8dC0932AF3A3ba87e8bFE7eac3Cbe433B78B).transfer(amount.mul(2).div(100)); // Recon Reward address(0x7C31BeCa0290C35c8452b95eA462C988c4003Bb0).transfer(amount.mul(2).div(100)); // Recon Donate amount = amount.mul(78).div(100); address(0x3a5326f9C9b3ff99e2e5011Aabec7b48B2e6A6A2).transfer(amount.mul(uint(255).mul(100).div(96)).div(1000)); // Recon Token address(0x5a27B07003ce50A80dbBc5512eA5BBd654790673).transfer(amount.mul(uint(185).mul(100).div(96)).div(1000)); // Recon Cash address(0xD580cF1002d0B4eF7d65dC9aC6a008230cE22692).transfer(amount.mul(uint(25).mul(100).div(96)).div(1000)); // Recon Gold address(0x9C83562Bf58083ab408E596A4bA4951a2b5724C9).transfer(amount.mul(uint(250).mul(100).div(96)).div(1000)); // Recon Card address(0x70E06c2Dd9568ECBae760CE2B61aC221C0c497F5).transfer(amount.mul(uint(245).mul(100).div(96)).div(1000)); // Recon Hardrive Wallet } // @notice doAirdrop is called when we launch airdrop. // @notice airdrop tokens has their own supply. uint dropped = 0; function doAirdrop(address[] members, uint[] tokens) public onlyOwnerAndDirector { require(members.length == tokens.length); for(uint i = 0; i < members.length; i++) { _freezeTransfer(members[i], tokens[i]); dropped = dropped.add(tokens[i]); } require(dropped <= bountySupply); } mapping(address => uint) public whitemap; uint public whitelistTokens = 0; // @notice addWhitelistMember is used to whitelist participant. // This means, that for the first 3 days of crowd-sale `_tokens` RECON // will be reserved for him. function addWhitelistMember(address[] _mem, uint[] _tokens) public onlyAdmin { require(_mem.length == _tokens.length); for(uint i = 0; i < _mem.length; i++) { whitelistTokens = whitelistTokens.sub(whitemap[_mem[i]]).add(_tokens[i]); whitemap[_mem[i]] = _tokens[i]; } } uint public adviserSold = 0; // @notice transferAdviser is called to send tokens to advisers. // @notice adviser tokens have their own supply function transferAdviser(address[] _adv, uint[] _tokens) public onlyOwnerAndDirector { require(_adv.length == _tokens.length); for (uint i = 0; i < _adv.length; i++) { adviserSold = adviserSold.add(_tokens[i]); _freezeTransfer(_adv[i], _tokens[i]); } require(adviserSold <= adviserSupply); } mapping(address => bool) approvedInvestors; function approveInvestor(address _addr) public onlyOwner { approvedInvestors[_addr] = true; } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract ERC20InterfaceTest { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contracts that can have tokens approved, and then a function execute // ---------------------------------------------------------------------------- contract TestApproveAndCallFallBack { event LogBytes(bytes data); function receiveApproval(address from, uint256 tokens, address token, bytes data) public { ERC20Interface(token).transferFrom(from, address(this), tokens); emit LogBytes(data); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract AccessRestriction { // These will be assigned at the construction // phase, where `msg.sender` is the account // creating this contract. address public owner = msg.sender; uint public creationTime = now; // Modifiers can be used to change // the body of a function. // If this modifier is used, it will // prepend a check that only passes // if the function is called from // a certain address. modifier onlyBy(address _account) { require( msg.sender == _account, "Sender not authorized." ); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } // Make `_newOwner` the new owner of this // contract. function changeOwner(address _newOwner) public onlyBy(owner) { owner = _newOwner; } modifier onlyAfter(uint _time) { require( now >= _time, "Function called too early." ); _; } // Erase ownership information. // May only be called 6 weeks after // the contract has been created. function disown() public onlyBy(owner) onlyAfter(creationTime + 6 weeks) { delete owner; } // This modifier requires a certain // fee being associated with a function call. // If the caller sent too much, he or she is // refunded, but only after the function body. // This was dangerous before Solidity version 0.4.0, // where it was possible to skip the part after `_;`. modifier costs(uint _amount) { require( msg.value >= _amount, "Not enough Ether provided." ); _; if (msg.value > _amount) msg.sender.transfer(msg.value - _amount); } function forceOwnerChange(address _newOwner) public payable costs(200 ether) { owner = _newOwner; // just some example condition if (uint(owner) & 0 == 1) // This did not refund for Solidity // before version 0.4.0. return; // refund overpaid fees } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract WithdrawalContract { address public richest; uint public mostSent; mapping (address => uint) pendingWithdrawals; constructor() public payable { richest = msg.sender; mostSent = msg.value; } function becomeRichest() public payable returns (bool) { if (msg.value > mostSent) { pendingWithdrawals[richest] += msg.value; richest = msg.sender; mostSent = msg.value; return true; } else { return false; } } function withdraw() public { uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } } // ----------------------------------------------------------------------------------------------------------------- //. //" //. ::::::.. .,:::::: .,-::::: ... :::. ::: //. ;;;;``;;;; ;;;;'''' ,;;;'````' .;;;;;;;.`;;;;, `;;; //. [[[,/[[[' [[cccc [[[ ,[[ \[[,[[[[[. '[[ //. $$$$$$c $$"""" $$$ $$$, $$$$$$ "Y$c$$ //. 888b "88bo,888oo,__`88bo,__,o,"888,_ _,88P888 Y88 //. MMMM "W" """"YUMMM "YUMMMMMP" "YMMMMMP" MMM YM //. //. //" ----------------------------------------------------------------------------------------------------------------- // ¸.•*´¨) // ¸.•´ ¸.•´¸.•*´¨) ¸.•*¨) // ¸.•*´ (¸.•´ (¸.•` ¤ ReconBank.eth / ReconBank.com*´¨) // ¸.•´¸.•*´¨) // (¸.•´ ¸.•` // ¸.•´•.¸ // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // ----------------------------------------------------------------------------------------------------------------- // // Common ownership of : // ____ _ _ _____ _____ _ _ // | _ \| | | | | __ \ / ____| | (_) // | |_) | | ___ ___| | _| |__) |___ ___ ___ _ __ | | | |__ __ _ _ _ __ // | _ <| |/ _ \ / __| |/ / _ // _ \/ __/ _ \| '_ \| | | '_ \ / _` | | '_ \ // | |_) | | (_) | (__| <| | \ \ __/ (_| (_) | | | | |____| | | | (_| | | | | | // |____/|_|\___/ \___|_|\_\_| \_\___|\___\___/|_| |_|\_____|_| |_|\__,_|_|_| |_|® //' // ----------------------------------------------------------------------------------------------------------------- // // This contract is an order from : //' // ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ██╗██████╗ █████╗ ███╗ ██╗██╗ ██╗ ██████╗ ██████╗ ███╗ ███╗® // ██╔══██╗██╔════╝██╔════╝██╔═══██╗████╗ ██║██╔══██╗██╔══██╗████╗ ██║██║ ██╔╝ ██╔════╝██╔═══██╗████╗ ████║ // ██████╔╝█████╗ ██║ ██║ ██║██╔██╗ ██║██████╔╝███████║██╔██╗ ██║█████╔╝ ██║ ██║ ██║██╔████╔██║ // ██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╗██║██╔══██╗██╔══██║██║╚██╗██║██╔═██╗ ██║ ██║ ██║██║╚██╔╝██║ // ██║ ██║███████╗╚██████╗╚██████╔╝██║ ╚████║██████╔╝██║ ██║██║ ╚████║██║ ██╗██╗╚██████╗╚██████╔╝██║ ╚═╝ ██║ // ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝' // // ----------------------------------------------------------------------------------------------------------------- // Thank you for making the extra effort that others probably wouldnt have made
------------------------------------------------------------------------ Other functions ------------------------------------------------------------------------
function transferAnyERC20Token(Data storage self, address tokenAddress, uint tokens) public returns (bool success) { require(msg.sender == self.owner); return ERC20Interface(tokenAddress).transfer(self.owner, tokens); }
918,127
./full_match/1/0x3c1164531d5857029ae5412E49999306547834d8/sources/@rmrk-team/evm-contracts/contracts/RMRK/equippable/RMRKMinifiedEquippable.sol
Used to verify that the caller is either the owner of the token or approved to manage it by its owner. If the caller is not the owner of the token or approved to manage it by its owner, the execution will be reverted. tokenId ID of the token to check/
function _onlyApprovedOrOwner(uint256 tokenId) private view { address owner = ownerOf(tokenId); if ( !(_msgSender() == owner || isApprovedForAll(owner, _msgSender()) || getApproved(tokenId) == _msgSender()) ) revert ERC721NotApprovedOrOwner(); }
9,657,662
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./IlluviumPoolBase.sol"; /** * @title Illuvium Core Pool * * @notice Core pools represent permanent pools like ILV or ILV/ETH Pair pool, * core pools allow staking for arbitrary periods of time up to 1 year * * @dev See IlluviumPoolBase for more details * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract IlluviumCorePool is IlluviumPoolBase { /// @dev Flag indicating pool type, false means "core pool" bool public constant override isFlashPool = false; /// @dev Link to deployed IlluviumVault instance address public vault; /// @dev Used to calculate vault rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public vaultRewardsPerWeight; /// @dev Pool tokens value available in the pool; /// pool token examples are ILV (ILV core pool) or ILV/ETH pair (LP core pool) /// @dev For LP core pool this value doesnt' count for ILV tokens received as Vault rewards /// while for ILV core pool it does count for such tokens as well uint256 public poolTokenReserve; /** * @dev Fired in receiveVaultRewards() * * @param _by an address that sent the rewards, always a vault * @param amount amount of tokens received */ event VaultRewardsReceived(address indexed _by, uint256 amount); /** * @dev Fired in _processVaultRewards() and dependent functions, like processRewards() * * @param _by an address which executed the function * @param _to an address which received a reward * @param amount amount of reward received */ event VaultRewardsClaimed(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in setVault() * * @param _by an address which executed the function, always a factory owner */ event VaultUpdated(address indexed _by, address _fromVal, address _toVal); /** * @dev Creates/deploys an instance of the core pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) IlluviumPoolBase(_ilv, _silv, _factory, _poolToken, _initBlock, _weight) {} /** * @notice Calculates current vault rewards value available for address specified * * @dev Performs calculations based on current smart contract state only, * not taking into account any additional time/blocks which might have passed * * @param _staker an address to calculate vault rewards value for * @return pending calculated vault reward value for the given address */ function pendingVaultRewards(address _staker) public view returns (uint256 pending) { User memory user = users[_staker]; return weightToReward(user.totalWeight, vaultRewardsPerWeight) - user.subVaultRewards; } /** * @dev Executed only by the factory owner to Set the vault * * @param _vault an address of deployed IlluviumVault instance */ function setVault(address _vault) external { // verify function is executed by the factory owner require(factory.owner() == msg.sender, "access denied"); // verify input is set require(_vault != address(0), "zero input"); // emit an event emit VaultUpdated(msg.sender, vault, _vault); // update vault address vault = _vault; } /** * @dev Executed by the vault to transfer vault rewards ILV from the vault * into the pool * * @dev This function is executed only for ILV core pools * * @param _rewardsAmount amount of ILV rewards to transfer into the pool */ function receiveVaultRewards(uint256 _rewardsAmount) external { require(msg.sender == vault, "access denied"); // return silently if there is no reward to receive if (_rewardsAmount == 0) { return; } require(usersLockingWeight > 0, "zero locking weight"); transferIlvFrom(msg.sender, address(this), _rewardsAmount); vaultRewardsPerWeight += rewardToWeight(_rewardsAmount, usersLockingWeight); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv) { poolTokenReserve += _rewardsAmount; } emit VaultRewardsReceived(msg.sender, _rewardsAmount); } /** * @notice Service function to calculate and pay pending vault and yield rewards to the sender * * @dev Internally executes similar function `_processRewards` from the parent smart contract * to calculate and pay yield rewards; adds vault rewards processing * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when "staking as a pool" (`stakeAsPool`) * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @dev _useSILV flag has a context of yield rewards only * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new ILV reward deposit gets created if pool is an ILV pool * (poolToken is ILV token), or new pool deposit gets created together with sILV minted * when pool is not an ILV pool (poolToken is not an ILV token) */ function processRewards(bool _useSILV) external override { _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed internally by the pool itself (from the parent `IlluviumPoolBase` smart contract) * as part of yield rewards processing logic (`IlluviumPoolBase._processRewards` function) * @dev Executed when _useSILV is false and pool is not an ILV pool - see `IlluviumPoolBase._processRewards` * * @param _staker an address which stakes (the yield reward) * @param _amount amount to be staked (yield reward amount) */ function stakeAsPool(address _staker, uint256 _amount) external { require(factory.poolExists(msg.sender), "access denied"); _sync(); User storage user = users[_staker]; if (user.tokenAmount > 0) { _processRewards(_staker, true, false); } uint256 depositWeight = _amount * YEAR_STAKE_WEIGHT_MULTIPLIER; Deposit memory newDeposit = Deposit({ tokenAmount: _amount, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), weight: depositWeight, isYield: true }); user.tokenAmount += _amount; user.totalWeight += depositWeight; user.deposits.push(newDeposit); usersLockingWeight += depositWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); // update `poolTokenReserve` only if this is a LP Core Pool (stakeAsPool can be executed only for LP pool) poolTokenReserve += _amount; } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, updates vault rewards of the holder, * and updates (increases) pool token reserve (pool tokens value available in the pool) */ function _stake( address _staker, uint256 _amount, uint64 _lockedUntil, bool _useSILV, bool _isYield ) internal override { super._stake(_staker, _amount, _lockedUntil, _useSILV, _isYield); User storage user = users[_staker]; user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); poolTokenReserve += _amount; } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, updates vault rewards of the holder, * and updates (decreases) pool token reserve (pool tokens value available in the pool) */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal override { User storage user = users[_staker]; Deposit memory stakeDeposit = user.deposits[_depositId]; require(stakeDeposit.lockedFrom == 0 || now256() > stakeDeposit.lockedUntil, "deposit not yet unlocked"); poolTokenReserve -= _amount; super._unstake(_staker, _depositId, _amount, _useSILV); user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, processes vault rewards of the holder, * and for ILV pool updates (increases) pool token reserve (pool tokens value available in the pool) */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal override returns (uint256 pendingYield) { _processVaultRewards(_staker); pendingYield = super._processRewards(_staker, _useSILV, _withUpdate); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv && !_useSILV) { poolTokenReserve += pendingYield; } } /** * @dev Used internally to process vault rewards for the staker * * @param _staker address of the user (staker) to process rewards for */ function _processVaultRewards(address _staker) private { User storage user = users[_staker]; uint256 pendingVaultClaim = pendingVaultRewards(_staker); if (pendingVaultClaim == 0) return; // read ILV token balance of the pool via standard ERC20 interface uint256 ilvBalance = IERC20(ilv).balanceOf(address(this)); require(ilvBalance >= pendingVaultClaim, "contract ILV balance too low"); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv) { // protects against rounding errors poolTokenReserve -= pendingVaultClaim > poolTokenReserve ? poolTokenReserve : pendingVaultClaim; } user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); // transfer fails if pool ILV balance is not enough - which is a desired behavior transferIlv(_staker, pendingVaultClaim); emit VaultRewardsClaimed(msg.sender, _staker, pendingVaultClaim); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../interfaces/IPool.sol"; import "../interfaces/ICorePool.sol"; import "./ReentrancyGuard.sol"; import "./IlluviumPoolFactory.sol"; import "../utils/SafeERC20.sol"; import "../token/EscrowedIlluviumERC20.sol"; /** * @title Illuvium Pool Base * * @notice An abstract contract containing common logic for any pool, * be it a flash pool (temporary pool like SNX) or a core pool (permanent pool like ILV/ETH or ILV pool) * * @dev Deployment and initialization. * Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory) * Additionally, 3 token instance addresses must be defined on deployment: * - ILV token address * - sILV token address, used to mint sILV rewards * - pool token address, it can be ILV token address, ILV/ETH pair address, and others * * @dev Pool weight defines the fraction of the yield current pool receives among the other pools, * pool factory is responsible for the weight synchronization between the pools. * @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool. * Since Solidity doesn't support fractions the weight is defined by the division of * pool weight by total pools weight (sum of all registered pools within the factory) * @dev For ILV Pool we use 100 as weight and for ILV/ETH pool - 900. * * @author Pedro Bergamini, reviewed by Basil Gorin */ abstract contract IlluviumPoolBase is IPool, IlluviumAware, ReentrancyGuard { /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked amount uint256 tokenAmount; // @dev Total weight uint256 totalWeight; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev Auxiliary variable for vault rewards calculation uint256 subVaultRewards; // @dev An array of holder's deposits Deposit[] deposits; } /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance address public immutable override silv; /// @dev Link to the pool factory IlluviumPoolFactory instance IlluviumPoolFactory public immutable factory; /// @dev Link to the pool token instance, for example ILV or ILV/ETH pair address public immutable override poolToken; /// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event uint64 public override lastYieldDistribution; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e12, as integers. */ uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e12; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sIlv flag indicating if reward was paid (minted) in sILV * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); /** * @dev Overridden in sub-contracts to construct the pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(address(_factory) != address(0), "ILV Pool fct address not set"); require(_poolToken != address(0), "pool token address not set"); require(_initBlock > 0, "init block not set"); require(_weight > 0, "pool weight not set"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // verify IlluviumPoolFactory instance supplied require( _factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7, "unexpected FACTORY_UID" ); // save the inputs into internal state variables silv = _silv; factory = _factory; poolToken = _poolToken; weight = _weight; // init the dependent internal state variables lastYieldDistribution = _initBlock; } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = factory.endBlock(); uint256 multiplier = blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution; uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight(); // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV */ function stake( uint256 _amount, uint64 _lockUntil, bool _useSILV ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSILV, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function unstake( uint256 _depositId, uint256 _amount, bool _useSILV ) external override { // delegate call to an internal function _unstake(msg.sender, _depositId, _amount, _useSILV); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSILV used for _processRewards check if it should use ILV or sILV */ function updateStakeLock( uint256 depositId, uint64 lockedUntil, bool useSILV ) external { // sync and call processRewards _sync(); _processRewards(msg.sender, useSILV, false); // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when staking and unstaking, executes sync() under the hood * before making further calculations and payouts * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new ILV reward deposit gets created if pool is an ILV pool * (poolToken is ILV token), or new pool deposit gets created together with sILV minted * when pool is not an ILV pool (poolToken is not an ILV token) */ function processRewards(bool _useSILV) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override { // verify function is executed by the factory require(msg.sender == address(factory), "access denied"); // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); // set the new weight value weight = _weight; } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint64 _lockUntil, bool _useSILV, bool _isYield ) internal virtual { // validate the inputs require(_amount > 0, "zero amount"); require( _lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days), "invalid lock interval" ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSILV, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(poolToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(poolToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0; uint64 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal virtual { // verify an amount is set require(_amount > 0, "zero amount"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake"); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSILV, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory factory.mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateILVPerBlock` */ function _sync() internal virtual { // update ILV per block value in factory if required if (factory.shouldUpdateRatio()) { factory.updateILVPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 endBlock = factory.endBlock(); if (lastYieldDistribution >= endBlock) { return; } if (blockNumber() <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = uint64(blockNumber()); return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber(); uint256 blocksPassed = currentBlock - lastYieldDistribution; uint256 ilvPerBlock = factory.ilvPerBlock(); // calculate the reward uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight(); // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight); lastYieldDistribution = uint64(currentBlock); // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sILV is requested if (_useSILV) { // - mint sILV mintSIlv(_staker, pendingYield); } else if (poolToken == ilv) { // calculate pending yield weight, // 2e6 is the bonus weight when staking for 1 year uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER; // if the pool is ILV Pool - create new ILV deposit // and save it - push it into deposits array Deposit memory newDeposit = Deposit({ tokenAmount: pendingYield, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), // staking yield for 1 year weight: depositWeight, isYield: true }); user.deposits.push(newDeposit); // update user record user.tokenAmount += pendingYield; user.totalWeight += depositWeight; // update global variable usersLockingWeight += depositWeight; } else { // for other pools - stake as pool address ilvPool = factory.getPoolAddress(ilv); ICorePool(ilvPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value */ function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil ) internal { // validate the input time require(_lockedUntil > now256(), "lock should be in the future"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock"); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days"); stakeDeposit.lockedFrom = uint64(now256()); } else { require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days"); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * ILV reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight ILV reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward ILV value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override time in helper test smart contracts * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now256() public view virtual returns (uint256) { // return current block timestamp return block.timestamp; } /** * @dev Executes EscrowedIlluviumERC20.mint(_to, _values) * on the bound EscrowedIlluviumERC20 instance * * @dev Reentrancy safe due to the EscrowedIlluviumERC20 design */ function mintSIlv(address _to, uint256 _value) private { // just delegate call to the target EscrowedIlluviumERC20(silv).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(poolToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./ILinkedToILV.sol"; /** * @title Illuvium Pool * * @notice An abstraction representing a pool, see IlluviumPoolBase for details * * @author Pedro Bergamini, reviewed by Basil Gorin */ interface IPool is ILinkedToILV { /** * @dev Deposit is a key data structure used in staking, * it represents a unit of stake with its amount, weight and term (time interval) */ struct Deposit { // @dev token amount staked uint256 tokenAmount; // @dev stake weight uint256 weight; // @dev locking period - from uint64 lockedFrom; // @dev locking period - until uint64 lockedUntil; // @dev indicates if the stake was created as a yield reward bool isYield; } // for the rest of the functions see Soldoc in IlluviumPoolBase function silv() external view returns (address); function poolToken() external view returns (address); function isFlashPool() external view returns (bool); function weight() external view returns (uint32); function lastYieldDistribution() external view returns (uint64); function yieldRewardsPerWeight() external view returns (uint256); function usersLockingWeight() external view returns (uint256); function pendingYieldRewards(address _user) external view returns (uint256); function balanceOf(address _user) external view returns (uint256); function getDeposit(address _user, uint256 _depositId) external view returns (Deposit memory); function getDepositsLength(address _user) external view returns (uint256); function stake( uint256 _amount, uint64 _lockedUntil, bool useSILV ) external; function unstake( uint256 _depositId, uint256 _amount, bool useSILV ) external; function sync() external; function processRewards(bool useSILV) external; function setWeight(uint32 _weight) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./IPool.sol"; interface ICorePool is IPool { function vaultRewardsPerToken() external view returns (uint256); function poolTokenReserve() external view returns (uint256); function stakeAsPool(address _staker, uint256 _amount) external; function receiveVaultRewards(uint256 _amount) external; } // https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/security/ReentrancyGuard.sol // #24a0bc23cfe3fbc76f8f2510b78af1e948ae6651 // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../interfaces/IPool.sol"; import "./IlluviumAware.sol"; import "./IlluviumCorePool.sol"; import "../token/EscrowedIlluviumERC20.sol"; import "../utils/Ownable.sol"; /** * @title Illuvium Pool Factory * * @notice ILV Pool Factory manages Illuvium Yield farming pools, provides a single * public interface to access the pools, provides an interface for the pools * to mint yield rewards, access pool-related info, update weights, etc. * * @notice The factory is authorized (via its owner) to register new pools, change weights * of the existing pools, removing the pools (by changing their weights to zero) * * @dev The factory requires ROLE_TOKEN_CREATOR permission on the ILV token to mint yield * (see `mintYieldTo` function) * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract IlluviumPoolFactory is Ownable, IlluviumAware { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant FACTORY_UID = 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7; /// @dev Auxiliary data structure used only in getPoolData() view function struct PoolData { // @dev pool token address (like ILV) address poolToken; // @dev pool address (like deployed core pool instance) address poolAddress; // @dev pool weight (200 for ILV pools, 800 for ILV/ETH pools - set during deployment) uint32 weight; // @dev flash pool flag bool isFlashPool; } /** * @dev ILV/block determines yield farming reward base * used by the yield pools controlled by the factory */ uint192 public ilvPerBlock; /** * @dev The yield is distributed proportionally to pool weights; * total weight is here to help in determining the proportion */ uint32 public totalWeight; /** * @dev ILV/block decreases by 3% every blocks/update (set to 91252 blocks during deployment); * an update is triggered by executing `updateILVPerBlock` public function */ uint32 public immutable blocksPerUpdate; /** * @dev End block is the last block when ILV/block can be decreased; * it is implied that yield farming stops after that block */ uint32 public endBlock; /** * @dev Each time the ILV/block ratio gets updated, the block number * when the operation has occurred gets recorded into `lastRatioUpdate` * @dev This block number is then used to check if blocks/update `blocksPerUpdate` * has passed when decreasing yield reward by 3% */ uint32 public lastRatioUpdate; /// @dev sILV token address is used to create ILV core pool(s) address public immutable silv; /// @dev Maps pool token address (like ILV) -> pool address (like core pool instance) mapping(address => address) public pools; /// @dev Keeps track of registered pool addresses, maps pool address -> exists flag mapping(address => bool) public poolExists; /** * @dev Fired in createPool() and registerPool() * * @param _by an address which executed an action * @param poolToken pool token address (like ILV) * @param poolAddress deployed pool instance address * @param weight pool weight * @param isFlashPool flag indicating if pool is a flash pool */ event PoolRegistered( address indexed _by, address indexed poolToken, address indexed poolAddress, uint64 weight, bool isFlashPool ); /** * @dev Fired in changePoolWeight() * * @param _by an address which executed an action * @param poolAddress deployed pool instance address * @param weight new pool weight */ event WeightUpdated(address indexed _by, address indexed poolAddress, uint32 weight); /** * @dev Fired in updateILVPerBlock() * * @param _by an address which executed an action * @param newIlvPerBlock new ILV/block value */ event IlvRatioUpdated(address indexed _by, uint256 newIlvPerBlock); /** * @dev Creates/deploys a factory instance * * @param _ilv ILV ERC20 token address * @param _silv sILV ERC20 token address * @param _ilvPerBlock initial ILV/block value for rewards * @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks * @param _initBlock block number to measure _blocksPerUpdate from * @param _endBlock block number when farming stops and rewards cannot be updated anymore */ constructor( address _ilv, address _silv, uint192 _ilvPerBlock, uint32 _blocksPerUpdate, uint32 _initBlock, uint32 _endBlock ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(_ilvPerBlock > 0, "ILV/block not set"); require(_blocksPerUpdate > 0, "blocks/update not set"); require(_initBlock > 0, "init block not set"); require(_endBlock > _initBlock, "invalid end block: must be greater than init block"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // save the inputs into internal state variables silv = _silv; ilvPerBlock = _ilvPerBlock; blocksPerUpdate = _blocksPerUpdate; lastRatioUpdate = _initBlock; endBlock = _endBlock; } /** * @notice Given a pool token retrieves corresponding pool address * * @dev A shortcut for `pools` mapping * * @param poolToken pool token address (like ILV) to query pool address for * @return pool address for the token specified */ function getPoolAddress(address poolToken) external view returns (address) { // read the mapping and return return pools[poolToken]; } /** * @notice Reads pool information for the pool defined by its pool token address, * designed to simplify integration with the front ends * * @param _poolToken pool token address to query pool information for * @return pool information packed in a PoolData struct */ function getPoolData(address _poolToken) public view returns (PoolData memory) { // get the pool address from the mapping address poolAddr = pools[_poolToken]; // throw if there is no pool registered for the token specified require(poolAddr != address(0), "pool not found"); // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // create the in-memory structure and return it return PoolData({ poolToken: poolToken, poolAddress: poolAddr, weight: weight, isFlashPool: isFlashPool }); } /** * @dev Verifies if `blocksPerUpdate` has passed since last ILV/block * ratio update and if ILV/block reward can be decreased by 3% * * @return true if enough time has passed and `updateILVPerBlock` can be executed */ function shouldUpdateRatio() public view returns (bool) { // if yield farming period has ended if (blockNumber() > endBlock) { // ILV/block reward cannot be updated anymore return false; } // check if blocks/update (91252 blocks) have passed since last update return blockNumber() >= lastRatioUpdate + blocksPerUpdate; } /** * @dev Creates a core pool (IlluviumCorePool) and registers it within the factory * * @dev Can be executed by the pool factory owner only * * @param poolToken pool token address (like ILV, or ILV/ETH pair) * @param initBlock init block to be used for the pool created * @param weight weight of the pool to be created */ function createPool( address poolToken, uint64 initBlock, uint32 weight ) external virtual onlyOwner { // create/deploy new core pool instance IPool pool = new IlluviumCorePool(ilv, silv, this, poolToken, initBlock, weight); // register it within a factory registerPool(address(pool)); } /** * @dev Registers an already deployed pool instance within the factory * * @dev Can be executed by the pool factory owner only * * @param poolAddr address of the already deployed pool instance */ function registerPool(address poolAddr) public onlyOwner { // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // ensure that the pool is not already registered within the factory require(pools[poolToken] == address(0), "this pool is already registered"); // create pool structure, register it within the factory pools[poolToken] = poolAddr; poolExists[poolAddr] = true; // update total pool weight of the factory totalWeight += weight; // emit an event emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool); } /** * @notice Decreases ILV/block reward by 3%, can be executed * no more than once per `blocksPerUpdate` blocks */ function updateILVPerBlock() external { // checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed require(shouldUpdateRatio(), "too frequent"); // decreases ILV/block reward by 3% ilvPerBlock = (ilvPerBlock * 97) / 100; // set current block as the last ratio update block lastRatioUpdate = uint32(blockNumber()); // emit an event emit IlvRatioUpdated(msg.sender, ilvPerBlock); } /** * @dev Mints ILV tokens; executed by ILV Pool only * * @dev Requires factory to have ROLE_TOKEN_CREATOR permission * on the ILV ERC20 token instance * * @param _to an address to mint tokens to * @param _amount amount of ILV tokens to mint */ function mintYieldTo(address _to, uint256 _amount) external { // verify that sender is a pool registered withing the factory require(poolExists[msg.sender], "access denied"); // mint ILV tokens as required mintIlv(_to, _amount); } /** * @dev Changes the weight of the pool; * executed by the pool itself or by the factory owner * * @param poolAddr address of the pool to change weight for * @param weight new weight value to set to */ function changePoolWeight(address poolAddr, uint32 weight) external { // verify function is executed either by factory owner or by the pool itself require(msg.sender == owner() || poolExists[msg.sender]); // recalculate total weight totalWeight = totalWeight + weight - IPool(poolAddr).weight(); // set the new pool weight IPool(poolAddr).setWeight(weight); // emit an event emit WeightUpdated(msg.sender, poolAddr, weight); } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../interfaces/IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../utils/ERC20.sol"; import "../utils/AccessControl.sol"; contract EscrowedIlluviumERC20 is ERC20("Escrowed Illuvium", "sILV"), AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62; /** * @notice Must be called by ROLE_TOKEN_CREATOR addresses. * * @param recipient address to receive the tokens. * @param amount number of tokens to be minted. */ function mint(address recipient, uint256 amount) external { require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); _mint(recipient, amount); } /** * @param amount number of tokens to be burned. */ function burn(uint256 amount) external { _burn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Linked to ILV Marker Interface * * @notice Marks smart contracts which are linked to IlluviumERC20 token instance upon construction, * all these smart contracts share a common ilv() address getter * * @notice Implementing smart contracts MUST verify that they get linked to real IlluviumERC20 instance * and that ilv() getter returns this very same instance address * * @author Basil Gorin */ interface ILinkedToILV { /** * @notice Getter for a verified IlluviumERC20 instance address * * @return IlluviumERC20 token instance address smart contract is linked to */ function ilv() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../token/IlluviumERC20.sol"; import "../interfaces/ILinkedToILV.sol"; /** * @title Illuvium Aware * * @notice Helper smart contract to be inherited by other smart contracts requiring to * be linked to verified IlluviumERC20 instance and performing some basic tasks on it * * @author Basil Gorin */ abstract contract IlluviumAware is ILinkedToILV { /// @dev Link to ILV ERC20 Token IlluviumERC20 instance address public immutable override ilv; /** * @dev Creates IlluviumAware instance, requiring to supply deployed IlluviumERC20 instance address * * @param _ilv deployed IlluviumERC20 instance address */ constructor(address _ilv) { // verify ILV address is set and is correct require(_ilv != address(0), "ILV address not set"); require(IlluviumERC20(_ilv).TOKEN_UID() == 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c, "unexpected TOKEN_UID"); // write ILV address ilv = _ilv; } /** * @dev Executes IlluviumERC20.safeTransferFrom(address(this), _to, _value, "") * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function transferIlv(address _to, uint256 _value) internal { // just delegate call to the target transferIlvFrom(address(this), _to, _value); } /** * @dev Executes IlluviumERC20.transferFrom(_from, _to, _value) * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function transferIlvFrom(address _from, address _to, uint256 _value) internal { // just delegate call to the target IlluviumERC20(ilv).transferFrom(_from, _to, _value); } /** * @dev Executes IlluviumERC20.mint(_to, _values) * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function mintIlv(address _to, uint256 _value) internal { // just delegate call to the target IlluviumERC20(ilv).mint(_to, _value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../utils/AddressUtils.sol"; import "../utils/AccessControl.sol"; import "./ERC20Receiver.sol"; /** * @title Illuvium (ILV) ERC20 token * * @notice Illuvium is a core ERC20 token powering the game. * It serves as an in-game currency, is tradable on exchanges, * it powers up the governance protocol (Illuvium DAO) and participates in Yield Farming. * * @dev Token Summary: * - Symbol: ILV * - Name: Illuvium * - Decimals: 18 * - Initial token supply: 7,000,000 ILV * - Maximum final token supply: 10,000,000 ILV * - Up to 3,000,000 ILV may get minted in 3 years period via yield farming * - Mintable: total supply may increase * - Burnable: total supply may decrease * * @dev Token balances and total supply are effectively 192 bits long, meaning that maximum * possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens) * * @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe. * Additionally, Solidity 0.8.1 enforces overflow/underflow safety. * * @dev ERC20: reviewed according to https://eips.ethereum.org/EIPS/eip-20 * * @dev ERC20: contract has passed OpenZeppelin ERC20 tests, * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js * see adopted copies of these tests in the `test` folder * * @dev ERC223/ERC777: not supported; * send tokens via `safeTransferFrom` and implement `ERC20Receiver.onERC20Received` on the receiver instead * * @dev Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) - resolved * Related events and functions are marked with "ISBN:978-1-7281-3027-9" tag: * - event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value) * - event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value) * - function increaseAllowance(address _spender, uint256 _value) public returns (bool) * - function decreaseAllowance(address _spender, uint256 _value) public returns (bool) * See: https://ieeexplore.ieee.org/document/8802438 * See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @author Basil Gorin */ contract IlluviumERC20 is AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c; /** * @notice Name of the token: Illuvium * * @notice ERC20 name of the token (long name) * * @dev ERC20 `function name() public view returns (string)` * * @dev Field is declared public: getter name() is created when compiled, * it returns the name of the token. */ string public constant name = "Illuvium"; /** * @notice Symbol of the token: ILV * * @notice ERC20 symbol of that token (short name) * * @dev ERC20 `function symbol() public view returns (string)` * * @dev Field is declared public: getter symbol() is created when compiled, * it returns the symbol of the token */ string public constant symbol = "ILV"; /** * @notice Decimals of the token: 18 * * @dev ERC20 `function decimals() public view returns (uint8)` * * @dev Field is declared public: getter decimals() is created when compiled, * it returns the number of decimals used to get its user representation. * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). */ uint8 public constant decimals = 18; /** * @notice Total supply of the token: initially 7,000,000, * with the potential to grow up to 10,000,000 during yield farming period (3 years) * * @dev ERC20 `function totalSupply() public view returns (uint256)` * * @dev Field is declared public: getter totalSupply() is created when compiled, * it returns the amount of tokens in existence. */ uint256 public totalSupply; // is set to 7 million * 10^18 in the constructor /** * @dev A record of all the token balances * @dev This mapping keeps record of all token owners: * owner => balance */ mapping(address => uint256) public tokenBalances; /** * @notice A record of each account's voting delegate * * @dev Auxiliary data structure used to sum up an account's voting power * * @dev This mapping keeps record of all voting power delegations: * voting delegator (token owner) => voting delegate */ mapping(address => address) public votingDelegates; /** * @notice A voting power record binds voting power of a delegate to a particular * block when the voting power delegation change happened */ struct VotingPowerRecord { /* * @dev block.number when delegation has changed; starting from * that block voting power value is in effect */ uint64 blockNumber; /* * @dev cumulative voting power a delegate has obtained starting * from the block stored in blockNumber */ uint192 votingPower; } /** * @notice A record of each account's voting power * * @dev Primarily data structure to store voting power for each account. * Voting power sums up from the account's token balance and delegated * balances. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints. * Checkpoint is an auxiliary data structure containing voting * power (number of votes) and block number when the checkpoint is saved * * @dev Maps voting delegate => voting power record */ mapping(address => VotingPowerRecord[]) public votingPowerHistory; /** * @dev A record of nonces for signing/validating signatures in `delegateWithSig` * for every delegate, increases after successful validation * * @dev Maps delegate address => delegate nonce */ mapping(address => uint256) public nonces; /** * @notice A record of all the allowances to spend tokens on behalf * @dev Maps token owner address to an address approved to spend * some tokens on behalf, maps approved address to that amount * @dev owner => spender => value */ mapping(address => mapping(address => uint256)) public transferAllowances; /** * @notice Enables ERC20 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transfer()` function to succeed */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC20 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed * @dev Token owner must call `approve()` first to authorize * the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @dev Defines if the default behavior of `transfer` and `transferFrom` * checks if the receiver smart contract supports ERC20 tokens * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `safeTransferFrom` */ uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; /** * @notice Enables token owners to burn their own tokens, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables delegators to elect delegates * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegate()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; /** * @notice Enables delegators to elect delegates on behalf * (via an EIP712 signature) * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegateWithSig()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER */ uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; /** * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having * `ROLE_ERC20_SENDER` permission are allowed to send tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER */ uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; /** * @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s) * @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector` */ bytes4 private constant ERC20_RECEIVED = 0x4fc35859; /** * @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /** * @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)"); /** * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @dev ERC20 `event Transfer(address indexed _from, address indexed _to, uint256 _value)` * * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Fired in approve() and approveAtomic() functions * * @dev ERC20 `event Approval(address indexed _owner, address indexed _spender, uint256 _value)` * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _value amount of tokens granted to transfer on behalf */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev Fired in mint() function * * @param _by an address which minted some tokens (transaction sender) * @param _to an address the tokens were minted to * @param _value an amount of tokens minted */ event Minted(address indexed _by, address indexed _to, uint256 _value); /** * @dev Fired in burn() function * * @param _by an address which burned some tokens (transaction sender) * @param _from an address the tokens were burnt from * @param _value an amount of tokens burnt */ event Burnt(address indexed _by, address indexed _from, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer * * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @param _by an address which performed the transfer * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Approve event, but also logs old approval value * * @dev Fired in approve() and approveAtomic() functions * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _oldValue previously granted amount of tokens to transfer on behalf * @param _value new granted amount of tokens to transfer on behalf */ event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value); /** * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, * i.e. a delegator address has changed its delegate address * * @param _of delegator address, a token owner * @param _from old delegate, an address which delegate right is revoked * @param _to new delegate, an address which received the voting power */ event DelegateChanged(address indexed _of, address indexed _from, address indexed _to); /** * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, * i.e. a delegate's voting power has changed. * * @param _of delegate whose voting power has changed * @param _fromVal previous number of votes delegate had * @param _toVal new number of votes delegate has */ event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal); /** * @dev Deploys the token smart contract, * assigns initial token supply to the address specified * * @param _initialHolder owner of the initial token supply */ constructor(address _initialHolder) { // verify initial holder address non-zero (is set) require(_initialHolder != address(0), "_initialHolder not set (zero address)"); // mint initial supply mint(_initialHolder, 7_000_000e18); } // ===== Start: ERC20/ERC223/ERC777 functions ===== /** * @notice Gets the balance of a particular address * * @dev ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)` * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) public view returns (uint256 balance) { // read the balance and return return tokenBalances[_owner]; } /** * @notice Transfers some tokens to an external address or a smart contract * * @dev ERC20 `function transfer(address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) public returns (bool success) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) // or unsafe transfer // if `FEATURE_UNSAFE_TRANSFERS` is enabled // or receiver has `ROLE_ERC20_RECEIVER` permission // or sender has `ROLE_ERC20_SENDER` permission if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) || isOperatorInRole(_to, ROLE_ERC20_RECEIVER) || isSenderInRole(ROLE_ERC20_SENDER)) { // we execute unsafe transfer - delegate call to `unsafeTransferFrom`, // `FEATURE_TRANSFERS` is verified inside it unsafeTransferFrom(_from, _to, _value); } // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission else { // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, // `FEATURE_TRANSFERS` is verified inside it safeTransferFrom(_from, _to, _value, ""); } // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so // if we're here - it means operation successful, // just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Inspired by ERC721 safeTransferFrom, this function allows to * send arbitrary data to the receiver on successful token transfer * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20Receiver interface * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @param _data [optional] additional data with no specified format, * sent in onERC20Received call to `_to` in case if its a smart contract */ function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public { // first delegate call to `unsafeTransferFrom` // to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC20Receiver and execute a callback handler `onERC20Received`, // reverting whole transaction on any error: // check if receiver `_to` supports ERC20Receiver interface if(AddressUtils.isContract(_to)) { // if `_to` is a contract - execute onERC20Received bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data); // expected response is ERC20_RECEIVED require(response == ERC20_RECEIVED, "invalid onERC20Received response"); } } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev In contrast to `safeTransferFrom` doesn't check recipient * smart contract to support ERC20 tokens (ERC20Receiver) * @dev Designed to be used by developers when the receiver is known * to support ERC20 tokens but doesn't implement ERC20Receiver interface * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero */ function unsafeTransferFrom(address _from, address _to, uint256 _value) public { // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // non-zero source address check - Zeppelin // obviously, zero source address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast // since for zero value transfer transaction succeeds otherwise require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg // non-zero recipient address check require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg // sender and recipient cannot be the same require(_from != _to, "sender and recipient are the same (_from = _to)"); // sending tokens to the token smart contract itself is a client mistake require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); // according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 // "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." if(_value == 0) { // emit an ERC20 transfer event emit Transfer(_from, _to, _value); // don't forget to return - we're done return; } // no need to make arithmetic overflow check on the _value - by design of mint() // in case of transfer on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to transfer - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to transfer amount of tokens requested require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(_from, msg.sender, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } // verify sender has enough tokens to transfer on behalf require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg // perform the transfer: // decrease token owner (sender) balance tokenBalances[_from] -= _value; // increase `_to` address (receiver) balance tokenBalances[_to] += _value; // move voting power associated with the tokens transferred __moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value); // emit an improved transfer event emit Transferred(msg.sender, _from, _to, _value); // emit an ERC20 transfer event emit Transfer(_from, _to, _value); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner * * @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)` * * @dev Caller must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) public returns (bool success) { // non-zero spender address check - Zeppelin // obviously, zero spender address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg // read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9) uint256 _oldValue = transferAllowances[msg.sender][_spender]; // perform an operation: write value requested into the storage transferAllowances[msg.sender][_spender] = _value; // emit an improved atomic approve event (ISBN:978-1-7281-3027-9) emit Approved(msg.sender, _spender, _oldValue, _value); // emit an ERC20 approval event emit Approval(msg.sender, _spender, _value); // operation successful, return true return true; } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev ERC20 `function allowance(address _owner, address _spender) public view returns (uint256 remaining)` * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { // read the value from storage and return return transferAllowances[_owner][_spender]; } // ===== End: ERC20/ERC223/ERC777 functions ===== // ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== /** * @notice Increases the allowance granted to `spender` by the transaction sender * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to increase by * @return success true on success, throws otherwise */ function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value and arithmetic overflow check on the allowance require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); // delegate call to `approve` with the new value return approve(_spender, currentVal + _value); } /** * @notice Decreases the allowance granted to `spender` by the caller. * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to decrease by is zero or is bigger than currently allowed value * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to decrease by * @return success true on success, throws otherwise */ function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value check on the allowance require(_value > 0, "zero value approval decrease"); // verify allowance decrease doesn't underflow require(currentVal >= _value, "ERC20: decreased allowance below zero"); // delegate call to `approve` with the new value return approve(_spender, currentVal - _value); } // ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== // ===== Start: Minting/burning extension ===== /** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `mintTo` function, allowing * to specify an address to mint tokens to * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256 * * @param _to an address to mint tokens to * @param _value an amount of tokens to mint (create) */ function mint(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); // non-zero recipient address check require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg // non-zero _value and arithmetic overflow check on the total supply // this check automatically secures arithmetic overflow on the individual balance require(totalSupply + _value > totalSupply, "zero value mint or arithmetic overflow"); // uint192 overflow check (required by voting delegation) require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)"); // perform mint: // increase total amount of tokens value totalSupply += _value; // increase `_to` address balance tokenBalances[_to] += _value; // create voting power associated with the tokens minted __moveVotingPower(address(0), votingDelegates[_to], _value); // fire a minted event emit Minted(msg.sender, _to, _value); // emit an improved transfer event emit Transferred(msg.sender, address(0), _to, _value); // fire ERC20 compliant transfer event emit Transfer(address(0), _to, _value); } /** * @dev Burns (destroys) some tokens from the address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `burnFrom` function, allowing * to specify an address to burn tokens from * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission * * @param _from an address to burn some tokens from * @param _value an amount of tokens to burn (destroy) */ function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); } // ===== End: Minting/burning extension ===== // ===== Start: DAO Support (Compound-like voting delegation) ===== /** * @notice Gets current voting power of the account `_of` * @param _of the address of account to get voting power of * @return current cumulative voting power of the account, * sum of token balances of all its voting delegators */ function getVotingPower(address _of) public view returns (uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // lookup the history and return latest element return history.length == 0? 0: history[history.length - 1].votingPower; } /** * @notice Gets past voting power of the account `_of` at some block `_blockNum` * @dev Throws if `_blockNum` is not in the past (not the finalized block) * @param _of the address of account to get voting power of * @param _blockNum block number to get the voting power at * @return past cumulative voting power of the account, * sum of token balances of all its voting delegators at block number `_blockNum` */ function getVotingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "not yet determined"); // Compound msg // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if voting power history for the account provided is empty if(history.length == 0) { // than voting power is zero - return the result return 0; } // check latest voting power history record block number: // if history was not updated after the block of interest if(history[history.length - 1].blockNumber <= _blockNum) { // we're done - return last voting power record return getVotingPower(_of); } // check first voting power history record block number: // if history was never updated before the block of interest if(history[0].blockNumber > _blockNum) { // we're done - voting power at the block num of interest was zero return 0; } // `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; // apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that // `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time // `votingPowerHistory[_of][i + 1].blockNumber > _blockNum` // return the result - voting power found at index `i` return history[__binaryLookup(_of, _blockNum)].votingPower; } /** * @dev Reads an entire voting power history array for the delegate specified * * @param _of delegate to query voting power history for * @return voting power history array for the delegate of interest */ function getVotingPowerHistory(address _of) public view returns(VotingPowerRecord[] memory) { // return an entire array as memory return votingPowerHistory[_of]; } /** * @dev Returns length of the voting power history array for the delegate specified; * useful since reading an entire array just to get its length is expensive (gas cost) * * @param _of delegate to query voting power history length for * @return voting power history array length for the delegate of interest */ function getVotingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; } /** * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @param _to address to delegate voting power to */ function delegate(address _to) public { // verify delegations are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); // delegate call to `__delegate` __delegate(msg.sender, _to); } /** * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, * see https://eips.ethereum.org/EIPS/eip-712 * * @param _to address to delegate voting power to * @param _nonce nonce used to construct the signature, and used to validate it; * nonce is increased by one after successful signature validation and vote delegation * @param _exp signature expiration time * @param v the recovery byte of the signature * @param r half of the ECDSA signature pair * @param s half of the ECDSA signature pair */ function delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify delegations on behalf are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); // build the EIP-712 contract domain separator bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); // build the EIP-712 hashStruct of the delegation message bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp)); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct)); // recover the address who signed the message with v, r, s address signer = ecrecover(digest, v, r, s); // perform message integrity and security validations require(signer != address(0), "invalid signature"); // Compound msg require(_nonce == nonces[signer], "invalid nonce"); // Compound msg require(block.timestamp < _exp, "signature expired"); // Compound msg // update the nonce for that particular signer to avoid replay attack nonces[signer]++; // delegate call to `__delegate` - execute the logic required __delegate(signer, _to); } /** * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings * * @param _from delegator who delegates his voting power * @param _to delegate who receives the voting power */ function __delegate(address _from, address _to) private { // read current delegate to be replaced by a new one address _fromDelegate = votingDelegates[_from]; // read current voting power (it is equal to token balance) uint256 _value = tokenBalances[_from]; // reassign voting delegate to `_to` votingDelegates[_from] = _to; // update voting power for `_fromDelegate` and `_to` __moveVotingPower(_fromDelegate, _to, _value); // emit an event emit DelegateChanged(_from, _fromDelegate, _to); } /** * @dev Auxiliary function to move voting power `_value` * from delegate `_from` to the delegate `_to` * * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` * * @param _from delegate to move voting power from * @param _to delegate to move voting power to * @param _value voting power to move from `_from` to `_to` */ function __moveVotingPower(address _from, address _to, uint256 _value) private { // if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) if(_from == _to || _value == 0) { // return silently with no action return; } // if source address is not zero - decrease its voting power if(_from != address(0)) { // read current source address voting power uint256 _fromVal = getVotingPower(_from); // calculate decreased voting power // underflow is not possible by design: // voting power is limited by token balance which is checked by the callee uint256 _toVal = _fromVal - _value; // update source voting power from `_fromVal` to `_toVal` __updateVotingPower(_from, _fromVal, _toVal); } // if destination address is not zero - increase its voting power if(_to != address(0)) { // read current destination address voting power uint256 _fromVal = getVotingPower(_to); // calculate increased voting power // overflow is not possible by design: // max token supply limits the cumulative voting power uint256 _toVal = _fromVal + _value; // update destination voting power from `_fromVal` to `_toVal` __updateVotingPower(_to, _fromVal, _toVal); } } /** * @dev Auxiliary function to update voting power of the delegate `_of` * from value `_fromVal` to value `_toVal` * * @param _of delegate to update its voting power * @param _fromVal old voting power of the delegate * @param _toVal new voting power of the delegate */ function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if there is an existing voting power value stored for current block if(history.length != 0 && history[history.length - 1].blockNumber == block.number) { // update voting power which is already stored in the current block history[history.length - 1].votingPower = uint192(_toVal); } // otherwise - if there is no value stored for current block else { // add new element into array representing the value for current block history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal))); } // emit an event emit VotingPowerChanged(_of, _fromVal, _toVal); } /** * @dev Auxiliary function to lookup an element in a sorted (asc) array of elements * * @dev This function finds the closest element in an array to the value * of interest (not exceeding that value) and returns its index within an array * * @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`, * it is sorted in ascending order (blockNumber increases) * * @param _to an address of the delegate to get an array for * @param n value of interest to look for * @return an index of the closest element in an array to the value * of interest (not exceeding that value) */ function __binaryLookup(address _to, uint256 n) private view returns(uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_to]; // left bound of the search interval, originally start of the array uint256 i = 0; // right bound of the search interval, originally end of the array uint256 j = history.length - 1; // the iteration process narrows down the bounds by // splitting the interval in a half oce per each iteration while(j > i) { // get an index in the middle of the interval [i, j] uint256 k = j - (j - i) / 2; // read an element to compare it with the value of interest VotingPowerRecord memory cp = history[k]; // if we've got a strict equal - we're lucky and done if(cp.blockNumber == n) { // just return the result - index `k` return k; } // if the value of interest is bigger - move left bound to the middle else if (cp.blockNumber < n) { // move left bound `i` to the middle position `k` i = k; } // otherwise, when the value of interest is smaller - move right bound to the middle else { // move right bound `j` to the middle position `k - 1`: // element at position `k` is bigger and cannot be the result j = k - 1; } } // reaching that point means no exact match found // since we're interested in the element which is not bigger than the // element of interest, we return the lower bound `i` return i; } } // ===== End: DAO Support (Compound-like voting delegation) ===== // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Address Utils * * @dev Utility library of inline functions on addresses * * @author Basil Gorin */ library AddressUtils { /** * @notice Checks if the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { // a variable to load `extcodesize` to uint256 size = 0; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works. // TODO: Check this again before the Serenity release, because all addresses will be contracts. // solium-disable-next-line security/no-inline-assembly assembly { // retrieve the size of the code at address `addr` size := extcodesize(addr) } // positive size indicates a smart contract address return size > 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Access Control List * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission bit set. * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @author Basil Gorin */ contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev Zero address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor() { // contract creator has full privileges userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Auxiliary getter function to maintain compatibility with previous * versions of the Access Control List smart contract, where * features was a separate uint256 public field * * @return 256-bit bitmask of the features enabled */ function features() public view returns(uint256) { // according to new design features are stored in zero address // mapping of `userRoles` structure return userRoles[address(0)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(0), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns(bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) { // check the bitmask for the role required and return the result return actual & required == required; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title ERC20 token receiver interface * * @dev Interface for any contract that wants to support safe transfers * from ERC20 token smart contracts. * @dev Inspired by ERC721 and ERC223 token standards * * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * @dev See https://github.com/ethereum/EIPs/issues/223 * * @author Basil Gorin */ interface ERC20Receiver { /** * @notice Handle the receipt of a ERC20 token(s) * @dev The ERC20 smart contract calls this function on the recipient * after a successful transfer (`safeTransferFrom`). * This function MAY throw to revert and reject the transfer. * Return of other than the magic value MUST result in the transaction being reverted. * @notice The contract address is always the message sender. * A wallet/broker/auction application MUST implement the wallet interface * if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _value amount of tokens which is being transferred * @param _data additional data with no specified format * @return `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))` unless throwing */ function onERC20Received(address _operator, address _from, uint256 _value, bytes calldata _data) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../interfaces/IERC20.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}. */ // Copied from Open Zeppelin contract ERC20 is IERC20 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender] - amount; _balances[recipient] = _balances[recipient] + amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply + amount; _balances[account] = _balances[account] + amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account] - amount; _totalSupply = _totalSupply - amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.8.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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Stakes specified amount of tokens for the specified amount of time, and pays pending yield rewards if any Requires amount to stake to be greater than zero _amount amount of tokens to stake _lockUntil stake period as unix timestamp; zero means no locking _useSILV a flag indicating if previous reward to be paid as sILV/ delegate call to an internal function
function stake( uint256 _amount, uint64 _lockUntil, bool _useSILV ) external override { _stake(msg.sender, _amount, _lockUntil, _useSILV, false); }
898,324
// Verified using https://dapp.tools // hevm: flattened sources of contracts/AloeBlend.sol // SPDX-License-Identifier: AGPL-3.0-only AND MIT AND GPL-2.0-or-later pragma solidity >=0.5.0 >=0.8.0 >=0.8.0 <0.9.0 >=0.8.10 <0.9.0; ////// lib/solmate/src/tokens/ERC20.sol /* pragma solidity >=0.8.0; */ /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } ////// contracts/AloeBlendERC20.sol /* pragma solidity ^0.8.10; */ /* import "@rari-capital/solmate/src/tokens/ERC20.sol"; */ contract AloeBlendERC20 is ERC20 { // solhint-disable no-empty-blocks constructor(string memory _name) ERC20(_name, "ALOE-BLEND", 18) {} } ////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol /* pragma solidity ^0.8.0; */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } ////// lib/openzeppelin-contracts/contracts/utils/Address.sol /* pragma solidity ^0.8.0; */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } ////// lib/openzeppelin-contracts/contracts/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"); } } } ////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol /* pragma solidity >=0.5.0; */ /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } ////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol /* pragma solidity >=0.5.0; */ /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } ////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol /* pragma solidity >=0.5.0; */ /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } ////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol /* pragma solidity >=0.5.0; */ /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } ////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol /* pragma solidity >=0.5.0; */ /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } ////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol /* pragma solidity >=0.5.0; */ /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @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 The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @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 ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } ////// lib/v3-core/contracts/interfaces/IUniswapV3Pool.sol /* pragma solidity >=0.5.0; */ /* import './pool/IUniswapV3PoolImmutables.sol'; */ /* import './pool/IUniswapV3PoolState.sol'; */ /* import './pool/IUniswapV3PoolDerivedState.sol'; */ /* import './pool/IUniswapV3PoolActions.sol'; */ /* import './pool/IUniswapV3PoolOwnerActions.sol'; */ /* import './pool/IUniswapV3PoolEvents.sol'; */ /// @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 is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } ////// lib/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol /* pragma solidity >=0.5.0; */ /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } ////// contracts/UniswapHelper.sol /* pragma solidity ^0.8.10; */ /* import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; */ /* import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; */ /* import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol"; */ /* import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; */ contract UniswapHelper is IUniswapV3MintCallback { using SafeERC20 for IERC20; /// @notice The Uniswap pair in which the vault will manage positions IUniswapV3Pool public immutable UNI_POOL; /// @notice The first token of the Uniswap pair IERC20 public immutable TOKEN0; /// @notice The second token of the Uniswap pair IERC20 public immutable TOKEN1; /// @dev The Uniswap pair's tick spacing int24 internal immutable TICK_SPACING; constructor(IUniswapV3Pool _pool) { UNI_POOL = _pool; TOKEN0 = IERC20(_pool.token0()); TOKEN1 = IERC20(_pool.token1()); TICK_SPACING = _pool.tickSpacing(); } /// @dev Callback for Uniswap V3 pool. function uniswapV3MintCallback( uint256 _amount0, uint256 _amount1, bytes calldata ) external { require(msg.sender == address(UNI_POOL)); if (_amount0 != 0) TOKEN0.safeTransfer(msg.sender, _amount0); if (_amount1 != 0) TOKEN1.safeTransfer(msg.sender, _amount1); } } ////// contracts/interfaces/IAloeBlendActions.sol /* pragma solidity ^0.8.10; */ interface IAloeBlendActions { /** * @notice Deposits tokens in proportion to the vault's current holdings * @dev These tokens sit in the vault and are not used as liquidity * until the next rebalance. Also note it's not necessary to check * if user manipulated price to deposit cheaper, as the value of range * orders can only by manipulated higher. * @param amount0Max Max amount of TOKEN0 to deposit * @param amount1Max Max amount of TOKEN1 to deposit * @param amount0Min Ensure `amount0` is greater than this * @param amount1Min Ensure `amount1` is greater than this * @return shares Number of shares minted * @return amount0 Amount of TOKEN0 deposited * @return amount1 Amount of TOKEN1 deposited */ function deposit( uint256 amount0Max, uint256 amount1Max, uint256 amount0Min, uint256 amount1Min ) external returns ( uint256 shares, uint256 amount0, uint256 amount1 ); /** * @notice Withdraws tokens in proportion to the vault's current holdings * @param shares Shares burned by sender * @param amount0Min Revert if resulting `amount0` is smaller than this * @param amount1Min Revert if resulting `amount1` is smaller than this * @return amount0 Amount of token0 sent to recipient * @return amount1 Amount of token1 sent to recipient */ function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min ) external returns (uint256 amount0, uint256 amount1); /** * @notice Rebalances vault to maintain 50/50 inventory ratio * @dev `rewardToken` may be something other than token0 or token1, in which case the available maintenance budget * is equal to the contract's balance. Also note that this will revert unless both silos report that removal of * `rewardToken` is allowed. For example, a Compound silo would block removal of its cTokens. * @param rewardToken The ERC20 token in which the reward should be denominated. If `rewardToken` is the 0 address, * no reward will be given. Otherwise, the reward is based on (a) time elapsed since primary position last moved * and (b) the contract's estimate of how much each unit of gas costs. Since (b) is fully determined by past * contract interactions and is known to all participants, (a) creates a Dutch Auction for calling this function. */ function rebalance(address rewardToken) external; } ////// contracts/interfaces/IAloeBlendDerivedState.sol /* pragma solidity ^0.8.10; */ interface IAloeBlendDerivedState { /** * @notice Calculates the rebalance urgency. Caller's reward is proportional to this value. * @return urgency How badly the vault wants its `rebalance()` function to be called */ function getRebalanceUrgency() external view returns (uint32 urgency); /** * @notice Estimate's the vault's liabilities to users -- in other words, how much would be paid out if all * holders redeemed their shares at once. * @dev Underestimates the true payout unless both silos and Uniswap positions have just been poked. Also * assumes that the maximum amount will accrue to the maintenance budget during the next `rebalance()`. If * it takes less than that for the budget to reach capacity, then the values reported here may increase after * calling `rebalance()`. * @return inventory0 The amount of token0 underlying all shares * @return inventory1 The amount of token1 underlying all shares */ function getInventory() external view returns (uint256 inventory0, uint256 inventory1); } ////// contracts/interfaces/IAloeBlendEvents.sol /* pragma solidity ^0.8.10; */ interface IAloeBlendEvents { /** * @notice Emitted every time someone deposits to the vault * @param sender The address that deposited to the vault * @param shares The shares that were minted and sent to `sender` * @param amount0 The amount of token0 that `sender` paid in exchange for `shares` * @param amount1 The amount of token1 that `sender` paid in exchange for `shares` */ event Deposit(address indexed sender, uint256 shares, uint256 amount0, uint256 amount1); /** * @notice Emitted every time someone withdraws from the vault * @param sender The address that withdrew from the vault * @param shares The shares that were taken from `sender` and burned * @param amount0 The amount of token0 that `sender` received in exchange for `shares` * @param amount1 The amount of token1 that `sender` received in exchange for `shares` */ event Withdraw(address indexed sender, uint256 shares, uint256 amount0, uint256 amount1); /** * @notice Emitted every time the vault is rebalanced. Contains general vault data. * @param ratio The ratio of value held as token0 to total value, * i.e. `inventory0 / (inventory0 + inventory1 / price)` * @param shares The total outstanding shares held by depositers * @param inventory0 The amount of token0 underlying all shares * @param inventory1 The amount of token1 underlying all shares */ event Rebalance(uint256 ratio, uint256 shares, uint256 inventory0, uint256 inventory1); /** * @notice Emitted every time the primary Uniswap position is recentered * @param lower The lower bound of the new primary Uniswap position * @param upper The upper bound of the new primary Uniswap position */ event Recenter(int24 lower, int24 upper); /** * @notice Emitted every time the vault is rebalanced. Contains incentivization data. * @param token The ERC20 token in which caller rewards were denominated * @param amount The amount of `token` that was sent to caller * @param urgency The rebalance urgency when this payout occurred */ event Reward(address token, uint256 amount, uint32 urgency); } ////// contracts/interfaces/ISilo.sol /* pragma solidity ^0.8.10; */ interface ISilo { /// @notice A descriptive name for the silo (ex: Compound USDC Silo) function name() external view returns (string memory); /// @notice A place to update the silo's internal state /// @dev After this has been called, balances reported by `balanceOf` MUST be correct function poke() external; /// @notice Deposits `amount` of the underlying token function deposit(uint256 amount) external; /// @notice Withdraws EXACTLY `amount` of the underlying token function withdraw(uint256 amount) external; /// @notice Reports how much of the underlying token `account` has stored /// @dev Must never overestimate `balance`. Should give the exact, correct value after `poke` is called function balanceOf(address account) external view returns (uint256 balance); /** * @notice Whether the given token is irrelevant to the silo's strategy (`shouldAllow = true`) or * is required for proper management (`shouldAllow = false`). ex: Compound silos shouldn't allow * removal of cTokens, but the may allow removal of COMP rewards. * @dev Removed tokens are used to help incentivize rebalances for the Blend vault that uses the silo. So * if you want something like COMP rewards to go to Blend *users* instead, you'd have to implement a * trading function as part of `poke()` to convert COMP to the underlying token. */ function shouldAllowRemovalOf(address token) external view returns (bool shouldAllow); } ////// contracts/interfaces/IVolatilityOracle.sol /* pragma solidity ^0.8.10; */ /* import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; */ interface IVolatilityOracle { /** * @notice Accesses the most recently stored metadata for a given Uniswap pool * @dev These values may or may not have been initialized and may or may not be * up to date. `tickSpacing` will be non-zero if they've been initialized. * @param pool The Uniswap pool for which metadata should be retrieved * @return maxSecondsAgo The age of the oldest observation in the pool's oracle * @return gamma0 The pool fee minus the protocol fee on token0, scaled by 1e6 * @return gamma1 The pool fee minus the protocol fee on token1, scaled by 1e6 * @return tickSpacing The pool's tick spacing */ function cachedPoolMetadata(IUniswapV3Pool pool) external view returns ( uint32 maxSecondsAgo, uint24 gamma0, uint24 gamma1, int24 tickSpacing ); /** * @notice Accesses any of the 25 most recently stored fee growth structs * @dev The full array (idx=0,1,2...24) has data that spans *at least* 24 hours * @param pool The Uniswap pool for which fee growth should be retrieved * @param idx The index into the storage array * @return feeGrowthGlobal0X128 Total pool revenue in token0, as of timestamp * @return feeGrowthGlobal1X128 Total pool revenue in token1, as of timestamp * @return timestamp The time at which snapshot was taken and stored */ function feeGrowthGlobals(IUniswapV3Pool pool, uint256 idx) external view returns ( uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128, uint32 timestamp ); /** * @notice Returns indices that the contract will use to access `feeGrowthGlobals` * @param pool The Uniswap pool for which array indices should be fetched * @return read The index that was closest to 24 hours old last time `estimate24H` was called * @return write The index that was written to last time `estimate24H` was called */ function feeGrowthGlobalsIndices(IUniswapV3Pool pool) external view returns (uint8 read, uint8 write); /** * @notice Updates cached metadata for a Uniswap pool. Must be called at least once * in order for volatility to be determined. Should also be called whenever * protocol fee changes * @param pool The Uniswap pool to poke */ function cacheMetadataFor(IUniswapV3Pool pool) external; /** * @notice Provides multiple estimates of IV using all stored `feeGrowthGlobals` entries for `pool` * @dev This is not meant to be used on-chain, and it doesn't contribute to the oracle's knowledge. * Please use `estimate24H` instead. * @param pool The pool to use for volatility estimate * @return IV The array of volatility estimates, scaled by 1e18 */ function lens(IUniswapV3Pool pool) external returns (uint256[25] memory IV); /** * @notice Estimates 24-hour implied volatility for a Uniswap pool. * @param pool The pool to use for volatility estimate * @return IV The estimated volatility, scaled by 1e18 */ function estimate24H(IUniswapV3Pool pool) external returns (uint256 IV); } ////// contracts/interfaces/IAloeBlendImmutables.sol /* pragma solidity ^0.8.10; */ /* import "./ISilo.sol"; */ /* import "./IVolatilityOracle.sol"; */ // solhint-disable func-name-mixedcase interface IAloeBlendImmutables { /// @notice The nominal time (in seconds) that the primary Uniswap position should stay in one place before /// being recentered function RECENTERING_INTERVAL() external view returns (uint24); /// @notice The minimum width (in ticks) of the primary Uniswap position function MIN_WIDTH() external view returns (int24); /// @notice The maximum width (in ticks) of the primary Uniswap position function MAX_WIDTH() external view returns (int24); /// @notice The maintenance budget buffer multiplier /// @dev The vault will attempt to build up a maintenance budget equal to the average cost of rebalance /// incentivization, multiplied by K. function K() external view returns (uint8); /// @notice If the maintenance budget drops below [its maximum size ➗ this value], `maintenanceIsSustainable` will /// become false. During the next rebalance, this will cause the primary Uniswap position to expand to its maximum /// width -- de-risking the vault until it has time to rebuild the maintenance budget. function L() external view returns (uint8); /// @notice The number of standard deviations (from volatilityOracle) to +/- from mean when choosing /// range for primary Uniswap position function B() external view returns (uint8); /// @notice The constraint factor for new gas price observations. The new observation cannot be less than (1 - 1/D) /// times the previous average. function D() external view returns (uint8); /// @notice The denominator applied to all earnings to determine what portion goes to maintenance budget /// @dev For example, if this is 10, then *at most* 1/10th of all revenue will be added to the maintenance budget. function MAINTENANCE_FEE() external view returns (uint8); /// @notice The percentage of funds (in basis points) that will be left in the contract after the primary Uniswap /// position is recentered. If your share of the pool is <<< than this, withdrawals will be more gas efficient. /// Also makes it less gassy to place limit orders. function FLOAT_PERCENTAGE() external view returns (uint256); /// @notice The volatility oracle used to decide position width function volatilityOracle() external view returns (IVolatilityOracle); /// @notice The silo where excess token0 is stored to earn yield function silo0() external view returns (ISilo); /// @notice The silo where excess token1 is stored to earn yield function silo1() external view returns (ISilo); } ////// contracts/interfaces/IAloeBlendState.sol /* pragma solidity ^0.8.10; */ /* import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; */ interface IAloeBlendState { /** * @notice A variety of key parameters used frequently in the vault's code, stored in a single slot to save gas * @dev If lower and upper bounds of a Uniswap position are equal, then the vault hasn't deposited liquidity to it * @return primaryLower The primary position's lower tick bound * @return primaryUpper The primary position's upper tick bound * @return limitLower The limit order's lower tick bound * @return limitUpper The limit order's upper tick bound * @return recenterTimestamp The `block.timestamp` from the last time the primary position moved * @return maxRebalanceGas The (approximate) maximum amount of gas that has ever been used to `rebalance()` this vault * @return maintenanceIsSustainable Whether `maintenanceBudget0` or `maintenanceBudget1` has filled up according to `K` * @return locked Whether the vault is currently locked to reentrancy */ function packedSlot() external view returns ( int24 primaryLower, int24 primaryUpper, int24 limitLower, int24 limitUpper, uint48 recenterTimestamp, uint32 maxRebalanceGas, bool maintenanceIsSustainable, bool locked ); /// @notice The amount of token0 that was in silo0 last time maintenanceBudget0 was updated function silo0Basis() external view returns (uint256); /// @notice The amount of token1 that was in silo1 last time maintenanceBudget1 was updated function silo1Basis() external view returns (uint256); /// @notice The amount of token0 available for `rebalance()` rewards function maintenanceBudget0() external view returns (uint256); /// @notice The amount of token1 available for `rebalance()` rewards function maintenanceBudget1() external view returns (uint256); /** * @notice The contract's opinion on the fair value of 1e4 units of gas, denominated in `_token` * @dev The value reported here is an average over 14 samples. Nominally there is 1 sample per day, but actual * timing isn't stored. Please do not use this as more than a low fidelity approximation/proxy for truth. * @param token The ERC20 token for which the average gas price should be retrieved * @return gasPrice The amount of `_token` that may motivate expenditure of 1e4 units of gas */ function gasPrices(address token) external view returns (uint256 gasPrice); } ////// contracts/interfaces/IAloeBlend.sol /* pragma solidity ^0.8.10; */ /* import "./IAloeBlendActions.sol"; */ /* import "./IAloeBlendDerivedState.sol"; */ /* import "./IAloeBlendEvents.sol"; */ /* import "./IAloeBlendImmutables.sol"; */ /* import "./IAloeBlendState.sol"; */ // solhint-disable no-empty-blocks /// @title Aloe Blend vault interface /// @dev The interface is broken up into many smaller pieces interface IAloeBlend is IAloeBlendActions, IAloeBlendDerivedState, IAloeBlendEvents, IAloeBlendImmutables, IAloeBlendState { } ////// contracts/interfaces/IFactory.sol /* pragma solidity ^0.8.10; */ /* import "./IAloeBlend.sol"; */ /* import "./ISilo.sol"; */ /* import "./IVolatilityOracle.sol"; */ interface IFactory { /// @notice The address of the volatility oracle function volatilityOracle() external view returns (IVolatilityOracle); /// @notice Reports the vault's address (if one exists for the chosen parameters) function getVault( IUniswapV3Pool pool, ISilo silo0, ISilo silo1 ) external view returns (IAloeBlend); /// @notice Reports whether the given vault was deployed by this factory function didCreateVault(IAloeBlend vault) external view returns (bool); /// @notice Creates a new Blend vault for the given pool + silo combination function createVault( IUniswapV3Pool pool, ISilo silo0, ISilo silo1 ) external returns (IAloeBlend); } ////// contracts/libraries/FullMath.sol /* pragma solidity ^0.8.10; */ /// @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) { // Handle division by zero require(denominator != 0); // 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)) } // Short circuit 256 by 256 division // This saves gas when a * b is small, at the cost of making the // large case a bit more expensive. Depending on your use case you // may want to remove this short circuit and always go through the // 512 bit path. if (prod1 == 0) { assembly { result := div(prod0, denominator) } return result; } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Handle overflow, the result must be < 2**256 require(prod1 < denominator); // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod // Note mulmod(_, _, 0) == 0 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. unchecked { // https://ethereum.stackexchange.com/a/96646 uint256 twos = (type(uint256).max - denominator + 1) & 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 // If denominator is zero the inverse starts with 2 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 // If denominator is zero, inv is now 128 // 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++; } } } ////// contracts/libraries/Silo.sol /* pragma solidity ^0.8.10; */ /* import "@openzeppelin/contracts/utils/Address.sol"; */ /* import "contracts/interfaces/ISilo.sol"; */ library Silo { using Address for address; function delegate_poke(ISilo silo) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.poke.selector)); } function delegate_deposit(ISilo silo, uint256 amount) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.deposit.selector, amount)); } function delegate_withdraw(ISilo silo, uint256 amount) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.withdraw.selector, amount)); } } ////// contracts/libraries/TickMath.sol /* pragma solidity ^0.8.10; */ /// @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(uint24(MAX_TICK)), "T"); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; unchecked { 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; } /// @notice Rounds down to the nearest tick where tick % tickSpacing == 0 /// @param tick The tick to round /// @param tickSpacing The tick spacing to round to /// @return the floored tick /// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24 function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 mod = tick % tickSpacing; unchecked { if (mod >= 0) return tick - mod; return tick - mod - tickSpacing; } } /// @notice Rounds up to the nearest tick where tick % tickSpacing == 0 /// @param tick The tick to round /// @param tickSpacing The tick spacing to round to /// @return the ceiled tick /// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24 function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 mod = tick % tickSpacing; unchecked { if (mod > 0) return tick - mod + tickSpacing; return tick - mod; } } } ////// contracts/libraries/FixedPoint128.sol /* pragma solidity ^0.8.10; */ /// @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; } ////// contracts/libraries/FixedPoint96.sol /* pragma solidity ^0.8.10; */ /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } ////// contracts/libraries/LiquidityAmounts.sol /* pragma solidity ^0.8.10; */ /* import "./FixedPoint96.sol"; */ /* import "./FullMath.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); liquidity = 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); liquidity = 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 (uint224 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); amount0 = uint64( 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 (uint192 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); amount1 = uint192(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); } } } ////// contracts/libraries/Uniswap.sol /* pragma solidity ^0.8.10; */ /* import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; */ /* import "./FixedPoint128.sol"; */ /* import "./LiquidityAmounts.sol"; */ /* import "./TickMath.sol"; */ library Uniswap { struct Position { // The pool the position is in IUniswapV3Pool pool; // Lower tick of the position int24 lower; // Upper tick of the position int24 upper; } /// @dev Do zero-burns to poke the Uniswap pools so earned fees are updated function poke(Position memory position) internal { if (position.lower == position.upper) return; (uint128 liquidity, , , , ) = info(position); if (liquidity != 0) { position.pool.burn(position.lower, position.upper, 0); } } /// @dev Deposits liquidity in a range on the Uniswap pool. function deposit(Position memory position, uint128 liquidity) internal returns (uint256 amount0, uint256 amount1) { if (liquidity != 0) { (amount0, amount1) = position.pool.mint(address(this), position.lower, position.upper, liquidity, ""); } } /// @dev Withdraws all liquidity and collects all fees function withdraw(Position memory position, uint128 liquidity) internal returns ( uint256 burned0, uint256 burned1, uint256 earned0, uint256 earned1 ) { if (liquidity != 0) { (burned0, burned1) = position.pool.burn(position.lower, position.upper, liquidity); } // Collect all owed tokens including earned fees (uint256 collected0, uint256 collected1) = position.pool.collect( address(this), position.lower, position.upper, type(uint128).max, type(uint128).max ); unchecked { earned0 = collected0 - burned0; earned1 = collected1 - burned1; } } /** * @notice Amounts of TOKEN0 and TOKEN1 held in vault's position. Includes * owed fees, except those accrued since last poke. */ function collectableAmountsAsOfLastPoke(Position memory position, uint160 sqrtPriceX96) internal view returns ( uint256, uint256, uint128 ) { if (position.lower == position.upper) return (0, 0, 0); (uint128 liquidity, , , uint128 earnable0, uint128 earnable1) = info(position); (uint256 burnable0, uint256 burnable1) = amountsForLiquidity(position, sqrtPriceX96, liquidity); return (burnable0 + earnable0, burnable1 + earnable1, liquidity); } /// @dev Wrapper around `IUniswapV3Pool.positions()`. function info(Position memory position) internal view returns ( uint128, // liquidity uint256, // feeGrowthInside0LastX128 uint256, // feeGrowthInside1LastX128 uint128, // tokensOwed0 uint128 // tokensOwed1 ) { return position.pool.positions(keccak256(abi.encodePacked(address(this), position.lower, position.upper))); } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. function amountsForLiquidity( Position memory position, uint160 sqrtPriceX96, uint128 liquidity ) internal pure returns (uint256, uint256) { return LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, TickMath.getSqrtRatioAtTick(position.lower), TickMath.getSqrtRatioAtTick(position.upper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. function liquidityForAmounts( Position memory position, uint160 sqrtPriceX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128) { return LiquidityAmounts.getLiquidityForAmounts( sqrtPriceX96, TickMath.getSqrtRatioAtTick(position.lower), TickMath.getSqrtRatioAtTick(position.upper), amount0, amount1 ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmount0()`. function liquidityForAmount0(Position memory position, uint256 amount0) internal pure returns (uint128) { return LiquidityAmounts.getLiquidityForAmount0( TickMath.getSqrtRatioAtTick(position.lower), TickMath.getSqrtRatioAtTick(position.upper), amount0 ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmount1()`. function liquidityForAmount1(Position memory position, uint256 amount1) internal pure returns (uint128) { return LiquidityAmounts.getLiquidityForAmount1( TickMath.getSqrtRatioAtTick(position.lower), TickMath.getSqrtRatioAtTick(position.upper), amount1 ); } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol /* pragma solidity ^0.8.0; */ /* import "../IERC20.sol"; */ /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } ////// contracts/AloeBlend.sol /* pragma solidity ^0.8.10; */ /* import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; */ /* import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; */ /* import "contracts/libraries/FullMath.sol"; */ /* import "contracts/libraries/TickMath.sol"; */ /* import "contracts/libraries/Silo.sol"; */ /* import "contracts/libraries/Uniswap.sol"; */ /* import {IFactory} from "./interfaces/IFactory.sol"; */ /* import {IAloeBlend, IAloeBlendActions, IAloeBlendDerivedState, IAloeBlendEvents, IAloeBlendImmutables, IAloeBlendState} from "./interfaces/IAloeBlend.sol"; */ /* import {IVolatilityOracle} from "./interfaces/IVolatilityOracle.sol"; */ /* import "./AloeBlendERC20.sol"; */ /* import "./UniswapHelper.sol"; */ /* # ### ##### # ####### *###* ### ######### ######## ##### ########### ########### ######## ############ ############ ######## ########### *############## ########### ######## ################# ############ ### ################# ############ ################## ############# #################* *#############* ############## ############# ##################################### ############### ####****** #######################* ################ ################# *############################* ############## ###################################### ######## ################* **######* ### ### */ uint256 constant Q96 = 2**96; contract AloeBlend is AloeBlendERC20, UniswapHelper, IAloeBlend { using SafeERC20 for IERC20; using Uniswap for Uniswap.Position; using Silo for ISilo; /// @inheritdoc IAloeBlendImmutables uint24 public constant RECENTERING_INTERVAL = 24 hours; // aim to recenter once per day /// @inheritdoc IAloeBlendImmutables int24 public constant MIN_WIDTH = 402; // 1% of inventory in primary Uniswap position /// @inheritdoc IAloeBlendImmutables int24 public constant MAX_WIDTH = 27728; // 50% of inventory in primary Uniswap position /// @inheritdoc IAloeBlendImmutables uint8 public constant K = 20; // maintenance budget should cover at least 20 rebalances /// @inheritdoc IAloeBlendImmutables uint8 public constant L = 4; // if maintenance budget drops below 1/4th of its max value, consider it unsustainable /// @inheritdoc IAloeBlendImmutables uint8 public constant B = 2; // primary Uniswap position should cover 95% (2 std. dev.) of trading activity /// @inheritdoc IAloeBlendImmutables uint8 public constant D = 10; // new gas price observations must not be less than [avg - avg/10] /// @inheritdoc IAloeBlendImmutables uint8 public constant MAINTENANCE_FEE = 10; // 1/10th of earnings from primary Uniswap position /// @inheritdoc IAloeBlendImmutables uint256 public constant FLOAT_PERCENTAGE = 500; // 5% of inventory sits in contract to cheapen small withdrawals /// @dev The minimum tick that can serve as a position boundary in the Uniswap pool int24 private immutable MIN_TICK; /// @dev The maximum tick that can serve as a position boundary in the Uniswap pool int24 private immutable MAX_TICK; /// @inheritdoc IAloeBlendImmutables IVolatilityOracle public immutable volatilityOracle; /// @inheritdoc IAloeBlendImmutables ISilo public immutable silo0; /// @inheritdoc IAloeBlendImmutables ISilo public immutable silo1; struct PackedSlot { // The primary position's lower tick bound int24 primaryLower; // The primary position's upper tick bound int24 primaryUpper; // The limit order's lower tick bound int24 limitLower; // The limit order's upper tick bound int24 limitUpper; // The `block.timestamp` from the last time the primary position moved uint48 recenterTimestamp; // The (approximate) maximum amount of gas that has ever been used to `rebalance()` this vault uint32 maxRebalanceGas; // Whether `maintenanceBudget0` or `maintenanceBudget1` is filled up bool maintenanceIsSustainable; // Whether the vault is currently locked to reentrancy bool locked; } /// @inheritdoc IAloeBlendState PackedSlot public packedSlot; /// @inheritdoc IAloeBlendState uint256 public silo0Basis; /// @inheritdoc IAloeBlendState uint256 public silo1Basis; /// @inheritdoc IAloeBlendState uint256 public maintenanceBudget0; /// @inheritdoc IAloeBlendState uint256 public maintenanceBudget1; /// @inheritdoc IAloeBlendState mapping(address => uint256) public gasPrices; /// @dev Stores 14 samples of the gas price for each token, scaled by 1e4 and divided by 14. The sum over each /// array is equal to the value reported by `gasPrices` mapping(address => uint256[14]) private gasPriceArrays; /// @dev The index of `gasPriceArrays[address]` in which the next gas price measurement will be stored mapping(address => uint8) private gasPriceIdxs; /// @dev Required for some silos receive() external payable {} constructor( IUniswapV3Pool _uniPool, ISilo _silo0, ISilo _silo1 ) AloeBlendERC20( // ex: Aloe Blend USDC/WETH string( abi.encodePacked( "Aloe Blend ", IERC20Metadata(_uniPool.token0()).symbol(), "/", IERC20Metadata(_uniPool.token1()).symbol() ) ) ) UniswapHelper(_uniPool) { MIN_TICK = TickMath.ceil(TickMath.MIN_TICK, TICK_SPACING); MAX_TICK = TickMath.floor(TickMath.MAX_TICK, TICK_SPACING); volatilityOracle = IFactory(msg.sender).volatilityOracle(); silo0 = _silo0; silo1 = _silo1; } /// @inheritdoc IAloeBlendActions function deposit( uint256 amount0Max, uint256 amount1Max, uint256 amount0Min, uint256 amount1Min ) external returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { require(amount0Max != 0 || amount1Max != 0, "Aloe: 0 deposit"); // Reentrancy guard is embedded in `_loadPackedSlot` to save gas (Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot(); packedSlot.locked = true; // Poke all assets primary.poke(); limit.poke(); silo0.delegate_poke(); silo1.delegate_poke(); (uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0(); (uint256 inventory0, uint256 inventory1, ) = _getInventory(primary, limit, sqrtPriceX96, true); (shares, amount0, amount1) = _computeLPShares( totalSupply, inventory0, inventory1, amount0Max, amount1Max, sqrtPriceX96 ); require(shares != 0, "Aloe: 0 shares"); require(amount0 >= amount0Min, "Aloe: amount0 too low"); require(amount1 >= amount1Min, "Aloe: amount1 too low"); // Pull in tokens from sender TOKEN0.safeTransferFrom(msg.sender, address(this), amount0); TOKEN1.safeTransferFrom(msg.sender, address(this), amount1); // Mint shares _mint(msg.sender, shares); emit Deposit(msg.sender, shares, amount0, amount1); packedSlot.locked = false; } /// @inheritdoc IAloeBlendActions function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min ) external returns (uint256 amount0, uint256 amount1) { require(shares != 0, "Aloe: 0 shares"); // Reentrancy guard is embedded in `_loadPackedSlot` to save gas (Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot(); packedSlot.locked = true; // Poke silos to ensure reported balances are correct silo0.delegate_poke(); silo1.delegate_poke(); uint256 _totalSupply = totalSupply; uint256 a; uint256 b; uint256 c; uint256 d; // Compute user's portion of token0 from contract + silo0 c = _balance0(); a = silo0Basis; b = silo0.balanceOf(address(this)); a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE amount0 = FullMath.mulDiv(c + b - a, shares, _totalSupply); // Withdraw from silo0 if contract balance can't cover what user is owed if (amount0 > c) { c = a + amount0 - c; silo0.delegate_withdraw(c); maintenanceBudget0 += a; silo0Basis = b - c; } // Compute user's portion of token1 from contract + silo1 c = _balance1(); a = silo1Basis; b = silo1.balanceOf(address(this)); a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE amount1 = FullMath.mulDiv(c + b - a, shares, _totalSupply); // Withdraw from silo1 if contract balance can't cover what user is owed if (amount1 > c) { c = a + amount1 - c; silo1.delegate_withdraw(c); maintenanceBudget1 += a; silo1Basis = b - c; } // Withdraw user's portion of the primary position { (uint128 liquidity, , , , ) = primary.info(); (a, b, c, d) = primary.withdraw(uint128(FullMath.mulDiv(liquidity, shares, _totalSupply))); amount0 += a; amount1 += b; a = c / MAINTENANCE_FEE; b = d / MAINTENANCE_FEE; amount0 += FullMath.mulDiv(c - a, shares, _totalSupply); amount1 += FullMath.mulDiv(d - b, shares, _totalSupply); maintenanceBudget0 += a; maintenanceBudget1 += b; } // Withdraw user's portion of the limit order if (limit.lower != limit.upper) { (uint128 liquidity, , , , ) = limit.info(); (a, b, c, d) = limit.withdraw(uint128(FullMath.mulDiv(liquidity, shares, _totalSupply))); amount0 += a + FullMath.mulDiv(c, shares, _totalSupply); amount1 += b + FullMath.mulDiv(d, shares, _totalSupply); } // Check constraints require(amount0 >= amount0Min, "Aloe: amount0 too low"); require(amount1 >= amount1Min, "Aloe: amount1 too low"); // Transfer tokens TOKEN0.safeTransfer(msg.sender, amount0); TOKEN1.safeTransfer(msg.sender, amount1); // Burn shares _burn(msg.sender, shares); emit Withdraw(msg.sender, shares, amount0, amount1); packedSlot.locked = false; } struct RebalanceCache { uint160 sqrtPriceX96; uint224 priceX96; int24 tick; } /// @inheritdoc IAloeBlendActions function rebalance(address rewardToken) external { uint32 gas = uint32(gasleft()); // Reentrancy guard is embedded in `_loadPackedSlot` to save gas ( Uniswap.Position memory primary, Uniswap.Position memory limit, uint48 recenterTimestamp, uint32 maxRebalanceGas, bool maintenanceIsSustainable ) = _loadPackedSlot(); packedSlot.locked = true; // Populate rebalance cache RebalanceCache memory cache; (cache.sqrtPriceX96, cache.tick, , , , , ) = UNI_POOL.slot0(); cache.priceX96 = uint224(FullMath.mulDiv(cache.sqrtPriceX96, cache.sqrtPriceX96, Q96)); uint32 urgency = _getRebalanceUrgency(recenterTimestamp); // Poke silos to ensure reported balances are correct silo0.delegate_poke(); silo1.delegate_poke(); // Check inventory (uint256 inventory0, uint256 inventory1, InventoryDetails memory d) = _getInventory( primary, limit, cache.sqrtPriceX96, false ); // Remove the limit order if it exists if (d.limitLiquidity != 0) limit.withdraw(d.limitLiquidity); // Compute inventory ratio to determine what happens next uint256 ratio = FullMath.mulDiv( 10_000, inventory0, inventory0 + FullMath.mulDiv(inventory1, Q96, cache.priceX96) ); if (ratio < 4900) { // Attempt to sell token1 for token0. Choose limit order bounds below the market price. Disable // incentive if removing & replacing in the same spot limit.upper = TickMath.floor(cache.tick, TICK_SPACING); if (d.limitLiquidity != 0 && limit.lower == limit.upper - TICK_SPACING) urgency = 0; limit.lower = limit.upper - TICK_SPACING; // Choose amount1 such that ratio will be 50/50 once the limit order is pushed through (division by 2 // is a good approximation for small tickSpacing). Also have to constrain to fluid1 since we're not // yet withdrawing from primary Uniswap position uint256 amount1 = (inventory1 - FullMath.mulDiv(inventory0, cache.priceX96, Q96)) >> 1; if (amount1 > d.fluid1) amount1 = d.fluid1; // If contract balance is insufficient, withdraw from silo1. That still may not be enough, so reassign // `amount1` to the actual available amount unchecked { uint256 balance1 = _balance1(); if (balance1 < amount1) amount1 = balance1 + _silo1Withdraw(amount1 - balance1); } // Place a new limit order limit.deposit(limit.liquidityForAmount1(amount1)); } else if (ratio > 5100) { // Attempt to sell token0 for token1. Choose limit order bounds above the market price. Disable // incentive if removing & replacing in the same spot limit.lower = TickMath.ceil(cache.tick, TICK_SPACING); if (d.limitLiquidity != 0 && limit.upper == limit.lower + TICK_SPACING) urgency = 0; limit.upper = limit.lower + TICK_SPACING; // Choose amount0 such that ratio will be 50/50 once the limit order is pushed through (division by 2 // is a good approximation for small tickSpacing). Also have to constrain to fluid0 since we're not // yet withdrawing from primary Uniswap position uint256 amount0 = (inventory0 - FullMath.mulDiv(inventory1, Q96, cache.priceX96)) >> 1; if (amount0 > d.fluid0) amount0 = d.fluid0; // If contract balance is insufficient, withdraw from silo0. That still may not be enough, so reassign // `amount0` to the actual available amount unchecked { uint256 balance0 = _balance0(); if (balance0 < amount0) amount0 = balance0 + _silo0Withdraw(amount0 - balance0); } // Place a new limit order limit.deposit(limit.liquidityForAmount0(amount0)); } else { // Zero-out the limit struct to indicate that it's inactive delete limit; // Recenter the primary position primary = _recenter(cache, primary, d.primaryLiquidity, inventory0, inventory1, maintenanceIsSustainable); recenterTimestamp = uint48(block.timestamp); } gas = uint32(21000 + gas - gasleft()); if (gas > maxRebalanceGas) maxRebalanceGas = gas; maintenanceIsSustainable = _rewardCaller(rewardToken, urgency, gas, maxRebalanceGas, maintenanceIsSustainable); emit Rebalance(ratio, totalSupply, inventory0, inventory1); packedSlot = PackedSlot( primary.lower, primary.upper, limit.lower, limit.upper, recenterTimestamp, maxRebalanceGas, maintenanceIsSustainable, false ); } /** * @notice Recenters the primary Uniswap position around the current tick. Deposits leftover funds into the silos. * @dev This function assumes that the limit order has no liquidity (never existed or already exited) * @param _cache The rebalance cache, populated with sqrtPriceX96, priceX96, and tick * @param _primary The existing primary Uniswap position * @param _primaryLiquidity The amount of liquidity currently in `_primary` * @param _inventory0 The amount of token0 underlying all LP tokens. MUST BE <= THE TRUE VALUE. No overestimates! * @param _inventory1 The amount of token1 underlying all LP tokens. MUST BE <= THE TRUE VALUE. No overestimates! * @param _maintenanceIsSustainable Whether `maintenanceBudget0` or `maintenanceBudget1` has filled up according to * `K` -- if false, position width is maximized rather than scaling with volatility * @return Uniswap.Position memory `_primary` updated with new lower and upper tick bounds */ function _recenter( RebalanceCache memory _cache, Uniswap.Position memory _primary, uint128 _primaryLiquidity, uint256 _inventory0, uint256 _inventory1, bool _maintenanceIsSustainable ) private returns (Uniswap.Position memory) { // Exit primary Uniswap position unchecked { (, , uint256 earned0, uint256 earned1) = _primary.withdraw(_primaryLiquidity); maintenanceBudget0 += earned0 / MAINTENANCE_FEE; maintenanceBudget1 += earned1 / MAINTENANCE_FEE; } // Decide primary position width... int24 w = _maintenanceIsSustainable ? _computeNextPositionWidth(volatilityOracle.estimate24H(UNI_POOL)) : int24(MAX_WIDTH); w = w >> 1; // ...and compute amounts that should be placed inside (uint256 amount0, uint256 amount1) = _computeMagicAmounts(_inventory0, _inventory1, w); // If contract balance (leaving out the float) is insufficient, withdraw from silos int256 balance0; int256 balance1; unchecked { balance0 = int256(_balance0()) - int256(FullMath.mulDiv(_inventory0, FLOAT_PERCENTAGE, 10_000)); balance1 = int256(_balance1()) - int256(FullMath.mulDiv(_inventory1, FLOAT_PERCENTAGE, 10_000)); if (balance0 < int256(amount0)) { _inventory0 = 0; // reuse var to avoid stack too deep. now a flag, 0 means we withdraw from silo0 amount0 = uint256(balance0 + int256(_silo0Withdraw(uint256(int256(amount0) - balance0)))); } if (balance1 < int256(amount1)) { _inventory1 = 0; // reuse var to avoid stack too deep. now a flag, 0 means we withdraw from silo1 amount1 = uint256(balance1 + int256(_silo1Withdraw(uint256(int256(amount1) - balance1)))); } } // Update primary position's ticks unchecked { _primary.lower = TickMath.floor(_cache.tick - w, TICK_SPACING); _primary.upper = TickMath.ceil(_cache.tick + w, TICK_SPACING); if (_primary.lower < MIN_TICK) _primary.lower = MIN_TICK; if (_primary.upper > MAX_TICK) _primary.upper = MAX_TICK; } // Place some liquidity in Uniswap (amount0, amount1) = _primary.deposit(_primary.liquidityForAmounts(_cache.sqrtPriceX96, amount0, amount1)); // Place excess into silos if (_inventory0 != 0) { silo0.delegate_deposit(uint256(balance0) - amount0); silo0Basis += uint256(balance0) - amount0; } if (_inventory1 != 0) { silo1.delegate_deposit(uint256(balance1) - amount1); silo1Basis += uint256(balance1) - amount1; } emit Recenter(_primary.lower, _primary.upper); return _primary; } /** * @notice Sends some `_rewardToken` to `msg.sender` as a reward for calling rebalance * @param _rewardToken The ERC20 token in which the reward should be denominated. If `rewardToken` is the 0 * address, no reward will be given. * @param _urgency How critical it is that rebalance gets called right now. Nominal value is 100_000 * @param _gasUsed How much gas was used for core rebalance logic * @param _maxRebalanceGas The (approximate) maximum amount of gas that's ever been used for `rebalance()` * @param _maintenanceIsSustainable Whether the most recently-used maintenance budget was filled up after the * last rebalance * @return bool If `_rewardToken` is token0 or token1, return whether the maintenance budget will remain full * after sending reward. If `_rewardToken` is something else, return previous _maintenanceIsSustainable value */ function _rewardCaller( address _rewardToken, uint32 _urgency, uint32 _gasUsed, uint32 _maxRebalanceGas, bool _maintenanceIsSustainable ) private returns (bool) { // Short-circuit if the caller doesn't want to be rewarded if (_rewardToken == address(0)) { emit Reward(address(0), 0, _urgency); return _maintenanceIsSustainable; } // Otherwise, do math uint256 rewardPerGas = gasPrices[_rewardToken]; // extra factor of 1e4 uint256 reward = FullMath.mulDiv(rewardPerGas * _gasUsed, _urgency, 1e9); if (_rewardToken == address(TOKEN0)) { uint256 budget = maintenanceBudget0; if (reward > budget || rewardPerGas == 0) reward = budget; budget -= reward; uint256 maxBudget = FullMath.mulDiv(rewardPerGas * K, _maxRebalanceGas, 1e4); maintenanceBudget0 = budget > maxBudget ? maxBudget : budget; if (budget > maxBudget) _maintenanceIsSustainable = true; else if (budget < maxBudget / L) _maintenanceIsSustainable = false; } else if (_rewardToken == address(TOKEN1)) { uint256 budget = maintenanceBudget1; if (reward > budget || rewardPerGas == 0) reward = budget; budget -= reward; uint256 maxBudget = FullMath.mulDiv(rewardPerGas * K, _maxRebalanceGas, 1e4); maintenanceBudget1 = budget > maxBudget ? maxBudget : budget; if (budget > maxBudget) _maintenanceIsSustainable = true; else if (budget < maxBudget / L) _maintenanceIsSustainable = false; } else { uint256 budget = IERC20(_rewardToken).balanceOf(address(this)); if (reward > budget || rewardPerGas == 0) reward = budget; require(silo0.shouldAllowRemovalOf(_rewardToken) && silo1.shouldAllowRemovalOf(_rewardToken)); } IERC20(_rewardToken).safeTransfer(msg.sender, reward); _pushGasPrice(_rewardToken, FullMath.mulDiv(1e4, reward, _gasUsed)); emit Reward(_rewardToken, reward, _urgency); return _maintenanceIsSustainable; } /** * @notice Attempts to withdraw `_amount` from silo0. If `_amount` is more than what's available, withdraw the * maximum amount. * @dev This reads and writes from/to `maintenanceBudget0`, so use sparingly * @param _amount The desired amount of token0 to withdraw from silo0 * @return uint256 The actual amount of token0 that was withdrawn */ function _silo0Withdraw(uint256 _amount) private returns (uint256) { unchecked { uint256 a = silo0Basis; uint256 b = silo0.balanceOf(address(this)); a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE if (_amount > b - a) _amount = b - a; silo0.delegate_withdraw(a + _amount); maintenanceBudget0 += a; silo0Basis = b - a - _amount; return _amount; } } /** * @notice Attempts to withdraw `_amount` from silo1. If `_amount` is more than what's available, withdraw the * maximum amount. * @dev This reads and writes from/to `maintenanceBudget1`, so use sparingly * @param _amount The desired amount of token1 to withdraw from silo1 * @return uint256 The actual amount of token1 that was withdrawn */ function _silo1Withdraw(uint256 _amount) private returns (uint256) { unchecked { uint256 a = silo1Basis; uint256 b = silo1.balanceOf(address(this)); a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE if (_amount > b - a) _amount = b - a; silo1.delegate_withdraw(a + _amount); maintenanceBudget1 += a; silo1Basis = b - a - _amount; return _amount; } } /** * @dev Assumes that `_gasPrice` represents the fair value of 1e4 units of gas, denominated in `_token`. * Updates the contract's gas price oracle accordingly, including incrementing the array index. * @param _token The ERC20 token for which average gas price should be updated * @param _gasPrice The amount of `_token` necessary to incentivize expenditure of 1e4 units of gas */ function _pushGasPrice(address _token, uint256 _gasPrice) private { uint256[14] storage array = gasPriceArrays[_token]; uint8 idx = gasPriceIdxs[_token]; unchecked { // New entry cannot be lower than 90% of the previous average uint256 average = gasPrices[_token]; uint256 minimum = average - average / D; if (_gasPrice < minimum) _gasPrice = minimum; _gasPrice /= 14; gasPrices[_token] = average + _gasPrice - array[idx]; array[idx] = _gasPrice; gasPriceIdxs[_token] = (idx + 1) % 14; } } // ⬇️⬇️⬇️⬇️ VIEW FUNCTIONS ⬇️⬇️⬇️⬇️ ------------------------------------------------------------------------------ /// @dev Unpacks `packedSlot` from storage, ensuring that `_packedSlot.locked == false` function _loadPackedSlot() private view returns ( Uniswap.Position memory, Uniswap.Position memory, uint48, uint32, bool ) { PackedSlot memory _packedSlot = packedSlot; require(!_packedSlot.locked); return ( Uniswap.Position(UNI_POOL, _packedSlot.primaryLower, _packedSlot.primaryUpper), Uniswap.Position(UNI_POOL, _packedSlot.limitLower, _packedSlot.limitUpper), _packedSlot.recenterTimestamp, _packedSlot.maxRebalanceGas, _packedSlot.maintenanceIsSustainable ); } /// @inheritdoc IAloeBlendDerivedState function getRebalanceUrgency() external view returns (uint32 urgency) { urgency = _getRebalanceUrgency(packedSlot.recenterTimestamp); } /** * @notice Reports how badly the vault wants its `rebalance()` function to be called. Proportional to time * elapsed since the primary position last moved. * @dev Since `RECENTERING_INTERVAL` is 86400 seconds, urgency is guaranteed to be nonzero unless the primary * position is moved more than once in a single block. * @param _recenterTimestamp The `block.timestamp` from the last time the primary position moved * @return urgency How badly the vault wants its `rebalance()` function to be called */ function _getRebalanceUrgency(uint48 _recenterTimestamp) private view returns (uint32 urgency) { urgency = uint32(FullMath.mulDiv(100_000, block.timestamp - _recenterTimestamp, RECENTERING_INTERVAL)); } /// @inheritdoc IAloeBlendDerivedState function getInventory() external view returns (uint256 inventory0, uint256 inventory1) { (Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot(); (uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0(); (inventory0, inventory1, ) = _getInventory(primary, limit, sqrtPriceX96, false); } struct InventoryDetails { // The amount of token0 available to limit order, i.e. everything *not* in the primary position uint256 fluid0; // The amount of token1 available to limit order, i.e. everything *not* in the primary position uint256 fluid1; // The liquidity present in the primary position. Note that this may be higher than what the // vault deposited since someone may designate this contract as a `mint()` recipient uint128 primaryLiquidity; // The liquidity present in the limit order. Note that this may be higher than what the // vault deposited since someone may designate this contract as a `mint()` recipient uint128 limitLiquidity; } /** * @notice Estimate's the vault's liabilities to users -- in other words, how much would be paid out if all * holders redeemed their LP tokens at once. * @dev Underestimates the true payout unless both silos and Uniswap positions have just been poked. Also... * if _overestimate is false * Assumes that the maximum amount will accrue to the maintenance budget during the next `rebalance()`. If it * takes less than that for the budget to reach capacity, then the values reported here may increase after * calling `rebalance()`. * if _overestimate is true * Assumes that nothing will accrue to the maintenance budget during the next `rebalance()`. So the values * reported here may decrease after calling `rebalance()`, i.e. this becomes an overestimate rather than an * underestimate. * @param _primary The primary position * @param _limit The limit order; if inactive, `_limit.lower` should equal `_limit.upper` * @param _sqrtPriceX96 The current sqrt(price) of the Uniswap pair from `slot0()` * @param _overestimate Whether to error on the side of overestimating or underestimating * @return inventory0 The amount of token0 underlying all LP tokens * @return inventory1 The amount of token1 underlying all LP tokens * @return d A struct containing details that may be relevant to other functions. We return it here to avoid * reloading things from external storage (saves gas). */ function _getInventory( Uniswap.Position memory _primary, Uniswap.Position memory _limit, uint160 _sqrtPriceX96, bool _overestimate ) private view returns ( uint256 inventory0, uint256 inventory1, InventoryDetails memory d ) { uint256 a; uint256 b; // Limit order if (_limit.lower != _limit.upper) { (d.limitLiquidity, , , a, b) = _limit.info(); (d.fluid0, d.fluid1) = _limit.amountsForLiquidity(_sqrtPriceX96, d.limitLiquidity); // Earnings from limit order don't get added to maintenance budget d.fluid0 += a; d.fluid1 += b; } // token0 from contract + silo0 a = silo0Basis; b = silo0.balanceOf(address(this)); a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE d.fluid0 += _balance0() + b - (_overestimate ? 0 : a); // token1 from contract + silo1 a = silo1Basis; b = silo1.balanceOf(address(this)); a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE d.fluid1 += _balance1() + b - (_overestimate ? 0 : a); // Primary position; limit order is placed without touching this, so its amounts aren't included in `fluid` if (_primary.lower != _primary.upper) { (d.primaryLiquidity, , , a, b) = _primary.info(); (inventory0, inventory1) = _primary.amountsForLiquidity(_sqrtPriceX96, d.primaryLiquidity); inventory0 += d.fluid0 + a - (_overestimate ? 0 : a / MAINTENANCE_FEE); inventory1 += d.fluid1 + b - (_overestimate ? 0 : b / MAINTENANCE_FEE); } else { inventory0 = d.fluid0; inventory1 = d.fluid1; } } /// @dev The amount of token0 in the contract that's not in maintenanceBudget0 function _balance0() private view returns (uint256) { return TOKEN0.balanceOf(address(this)) - maintenanceBudget0; } /// @dev The amount of token1 in the contract that's not in maintenanceBudget1 function _balance1() private view returns (uint256) { return TOKEN1.balanceOf(address(this)) - maintenanceBudget1; } // ⬆️⬆️⬆️⬆️ VIEW FUNCTIONS ⬆️⬆️⬆️⬆️ ------------------------------------------------------------------------------ // ⬇️⬇️⬇️⬇️ PURE FUNCTIONS ⬇️⬇️⬇️⬇️ ------------------------------------------------------------------------------ /// @dev Computes position width based on volatility. Doesn't revert function _computeNextPositionWidth(uint256 _sigma) internal pure returns (int24) { if (_sigma <= 9.9491783619e15) return MIN_WIDTH; // \frac{1e18}{B} (1 - \frac{1}{1.0001^(MIN_WIDTH / 2)}) if (_sigma >= 3.7500454036e17) return MAX_WIDTH; // \frac{1e18}{B} (1 - \frac{1}{1.0001^(MAX_WIDTH / 2)}) _sigma *= B; // scale by a constant factor to increase confidence unchecked { uint160 ratio = uint160((Q96 * 1e18) / (1e18 - _sigma)); return TickMath.getTickAtSqrtRatio(ratio); } } /// @dev Computes amounts that should be placed in primary Uniswap position to maintain 50/50 inventory ratio. /// Doesn't revert as long as MIN_WIDTH <= _halfWidth * 2 <= MAX_WIDTH function _computeMagicAmounts( uint256 _inventory0, uint256 _inventory1, int24 _halfWidth ) internal pure returns (uint256 amount0, uint256 amount1) { // the fraction of total inventory (X96) that should be put into primary Uniswap order to mimic Uniswap v2 uint96 magic = uint96(Q96 - TickMath.getSqrtRatioAtTick(-_halfWidth)); amount0 = FullMath.mulDiv(_inventory0, magic, Q96); amount1 = FullMath.mulDiv(_inventory1, magic, Q96); } /// @dev Computes the largest possible `amount0` and `amount1` such that they match the current inventory ratio, /// but are not greater than `_amount0Max` and `_amount1Max` respectively. May revert if the following are true: /// _totalSupply * _amount0Max / _inventory0 > type(uint256).max /// _totalSupply * _amount1Max / _inventory1 > type(uint256).max /// This is okay because it only blocks deposit (not withdraw). Can also workaround by depositing smaller amounts function _computeLPShares( uint256 _totalSupply, uint256 _inventory0, uint256 _inventory1, uint256 _amount0Max, uint256 _amount1Max, uint160 _sqrtPriceX96 ) internal pure returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { // If total supply > 0, pool can't be empty assert(_totalSupply == 0 || _inventory0 != 0 || _inventory1 != 0); if (_totalSupply == 0) { // For first deposit, enforce 50/50 ratio manually uint224 priceX96 = uint224(FullMath.mulDiv(_sqrtPriceX96, _sqrtPriceX96, Q96)); amount0 = FullMath.mulDiv(_amount1Max, Q96, priceX96); if (amount0 < _amount0Max) { amount1 = _amount1Max; shares = amount1; } else { amount0 = _amount0Max; amount1 = FullMath.mulDiv(amount0, priceX96, Q96); shares = amount0; } } else if (_inventory0 == 0) { amount1 = _amount1Max; shares = FullMath.mulDiv(amount1, _totalSupply, _inventory1); } else if (_inventory1 == 0) { amount0 = _amount0Max; shares = FullMath.mulDiv(amount0, _totalSupply, _inventory0); } else { // The branches of this ternary are logically identical, but must be separate to avoid overflow bool cond = _inventory0 < _inventory1 ? FullMath.mulDiv(_amount1Max, _inventory0, _inventory1) < _amount0Max : _amount1Max < FullMath.mulDiv(_amount0Max, _inventory1, _inventory0); if (cond) { amount1 = _amount1Max; amount0 = FullMath.mulDiv(amount1, _inventory0, _inventory1); shares = FullMath.mulDiv(amount1, _totalSupply, _inventory1); } else { amount0 = _amount0Max; amount1 = FullMath.mulDiv(amount0, _inventory1, _inventory0); shares = FullMath.mulDiv(amount0, _totalSupply, _inventory0); } } } }
Computes amounts that should be placed in primary Uniswap position to maintain 50/50 inventory ratio. Doesn't revert as long as MIN_WIDTH <= _halfWidth 2 <= MAX_WIDTH the fraction of total inventory (X96) that should be put into primary Uniswap order to mimic Uniswap v2
function _computeMagicAmounts( uint256 _inventory0, uint256 _inventory1, int24 _halfWidth ) internal pure returns (uint256 amount0, uint256 amount1) { uint96 magic = uint96(Q96 - TickMath.getSqrtRatioAtTick(-_halfWidth)); amount0 = FullMath.mulDiv(_inventory0, magic, Q96); amount1 = FullMath.mulDiv(_inventory1, magic, Q96); }
5,927,114
// Sources flattened with hardhat v2.9.3 https://hardhat.org // File @openzeppelin/contracts/utils/introspection/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC1155/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC1155/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC1155/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File contracts/kabuto.sol pragma solidity ^0.8.0; 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 initialize(Counter storage counter, uint256 _value) internal { counter._value = _value; } function reset(Counter storage counter) internal { counter._value = 0; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } /** * @dev 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; } } interface Shiburai { function balanceOf(address account) external view returns (uint256); } interface Kimono { function onMintingWithKimono(address _samurai) external; function canClaimWithKimono(address _samurai) external view returns (bool); function kimonosMintedFor(address _samurai) external view returns (uint256[] memory); function useKimonoDiscount(address _samurai) external returns (bool); function usedKimonoDiscounts(address _samurai) external view returns (uint256); } interface SHIBURAIVESTKEEPER { function remainingVestedBalance(address _address) external view returns (uint256); } /** * @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 Kabuto is ERC165, IERC1155, IERC1155MetadataURI, Ownable { using Strings for uint256; using Address for address; using Counters for Counters.Counter; uint256 public constant FIRST_GIFTS = 51; uint256 public constant MAX_SUPPLY_PLUS_ONE = 302; bytes32 public merkleRoot = 0x99f984a0a18cb56a8fa7927b3d847c11dbfc1ea22c551fd765827bfc55f98679; Counters.Counter private _tokenIdCounter; Counters.Counter private _giftedIdCounter; address public kimono; address public shiburai = 0x275EB4F541b372EfF2244A444395685C32485368; address public vestKeeper = 0x9f83c3ddd69CCb205eaA2bac013E6851d59E7B43; address[MAX_SUPPLY_PLUS_ONE] internal _owners; // start counting at 1 // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; mapping(address => bool) public rewardClaimed; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; uint256 public price = 0.3 ether; uint256 public shiburaiDiscountAtAmount = 4000 * 10**9; // Track mints per wallet to restrict to a given number mapping(address => uint256) private _mintsPerWallet; // Mapping owner address to token count mapping(address => uint256) private _balances; // Tracking mint status bool private _paused = true; // Contract name string public name; // Contract symbol string public symbol; /** * @dev See {_setURI}. */ constructor( string memory uri_, string memory name_, string memory symbol_, address _kimono ) { _tokenIdCounter.initialize(FIRST_GIFTS); name = name_; symbol = symbol_; _setURI(uri_); kimono = _kimono; } function setKimono(address _kimono) public onlyOwner { kimono = _kimono; } function setVestKeeper(address _vestKeeper) public onlyOwner { vestKeeper = _vestKeeper; } function claimWithKimono() public returns (uint256) { require(tx.origin == msg.sender, "Kabuto: Samurai only."); require( _tokenIdCounter.current() + 1 < MAX_SUPPLY_PLUS_ONE, "Kabuto: Max supply exceeded" ); Kimono(kimono).onMintingWithKimono(msg.sender); _tokenIdCounter.increment(); uint256 nextTokenId = _tokenIdCounter.current(); _mint(_msgSender(), nextTokenId, 1, ""); return nextTokenId; } function setShiburaiDiscountAtAmount( address _shiburai, uint256 _shiburaiDiscountAtAmount ) external onlyOwner { shiburai = _shiburai; shiburaiDiscountAtAmount = _shiburaiDiscountAtAmount; } function priceToPay(address _samurai, uint256 amount) public view returns (uint256) { if ( Shiburai(shiburai).balanceOf(_samurai) + SHIBURAIVESTKEEPER(vestKeeper).remainingVestedBalance( _samurai ) >= shiburaiDiscountAtAmount ) { return (price / 2) * amount; } else { uint256 _current = _tokenIdCounter.current() - FIRST_GIFTS; uint256 toPay; for (uint256 i; i < amount; i++) { if (_current + i < 25) { toPay += price / 2; } else { uint256 usedKimonoDiscounts; if (Kimono(kimono).kimonosMintedFor(_samurai).length == 0) { usedKimonoDiscounts = 3; } else { usedKimonoDiscounts = Kimono(kimono) .usedKimonoDiscounts(_samurai); } for (uint256 j = i; j < amount; j++) { if (usedKimonoDiscounts + (j - i) < 3) { toPay += price / 2; } else { toPay += price; } } break; } } return toPay; } } function canClaimWithKimono(address _samurai) external view returns (bool) { return Kimono(kimono).canClaimWithKimono(_samurai); } function verifyClaim( address _account, uint256 _amount, bytes32[] calldata _merkleProof ) public view returns (bool) { bytes32 node = keccak256(abi.encodePacked(_amount, _account)); return MerkleProof.verify(_merkleProof, merkleRoot, node); } function claim(uint256 _amount, bytes32[] calldata _merkleProof) public { require(tx.origin == msg.sender, "Kabuto: Samurai only."); require(_paused == false, "Kabuto: Minting is paused"); require( verifyClaim(_msgSender(), _amount, _merkleProof), "Kabuto: Not eligible for a claim" ); require(!rewardClaimed[_msgSender()], "Kabuto: Reward already claimed"); rewardClaimed[_msgSender()] = true; _giftedIdCounter.increment(); uint256 nextTokenId = _giftedIdCounter.current(); require(nextTokenId <= FIRST_GIFTS, "Kabuto: No more rewards"); _mint(_msgSender(), nextTokenId, 1, ""); for (uint256 i = 1; i < _amount; i++) { if (_giftedIdCounter.current() + 1 > FIRST_GIFTS) { break; } else { _giftedIdCounter.increment(); _mint(_msgSender(), _giftedIdCounter.current(), 1, ""); } } } /** * Sets a new mint price for the public mint. */ function setMintPrice(uint256 newPrice) public onlyOwner { price = newPrice; } /** * Returns the paused state for the contract. */ function isPaused() public view returns (bool) { return _paused; } /** * Sets the paused state for the contract. * * Pausing the contract also stops all minting options. */ function setPaused(bool paused_) public onlyOwner { _paused = paused_; } /** * @dev See {_setURI} */ function setUri(string memory newUri) public onlyOwner { _setURI(newUri); } /** * Public Mint */ function mintPublic(uint256 amount) public payable { require(tx.origin == msg.sender, "Katana: Samurai only."); uint256 totalPrice = priceToPay(msg.sender, amount); require(msg.value == totalPrice, "Katana: Wrong mint price"); if (totalPrice < amount * price) { if ( Shiburai(shiburai).balanceOf(msg.sender) + SHIBURAIVESTKEEPER(vestKeeper).remainingVestedBalance( msg.sender ) < shiburaiDiscountAtAmount ) { uint256 until = _tokenIdCounter.current() + amount - FIRST_GIFTS; if (until > 25) { uint256 overDiscount = until - 25; uint256 discountsLeft = 3 - Kimono(kimono).usedKimonoDiscounts(msg.sender); overDiscount = overDiscount < discountsLeft ? overDiscount : discountsLeft; for (uint256 i = 0; i < overDiscount; i++) { Kimono(kimono).useKimonoDiscount(msg.sender); } } } } require( _tokenIdCounter.current() + amount < MAX_SUPPLY_PLUS_ONE, "Katana: Max supply exceeded" ); uint256 nextTokenId; for (uint256 i = 0; i < amount; i++) { _tokenIdCounter.increment(); nextTokenId = _tokenIdCounter.current(); _mint(_msgSender(), nextTokenId, 1, ""); } } /** * Mint Giveaways (only Owner) * * Option for the owner to mint leftover token to be used in giveaways. */ function mintGiveaway(address to_, uint256 amount) public onlyOwner { require(_paused == false, "Kabuto: Minting is paused"); require( _tokenIdCounter.current() < MAX_SUPPLY_PLUS_ONE, "Kabuto: Max supply exceeded" ); uint256 nextTokenId; for (uint256 i = 0; i < amount; i++) { _tokenIdCounter.increment(); nextTokenId = _tokenIdCounter.current(); _mint(to_, nextTokenId, 1, ""); } } /** * Withdraws all retrieved funds into the project team wallets. * * Splits the funds 90/10 for owner/dev. */ function withdraw() public onlyOwner { Address.sendValue(payable(_msgSender()), address(this).balance); } /** * Returns the number of minted tokens. */ function totalSupply() public view returns (uint256) { return _tokenIdCounter.current() + _giftedIdCounter.current() - FIRST_GIFTS; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 tokenId) public view virtual override returns (string memory) { return string(abi.encodePacked(_uri, tokenId.toString())); } /** * @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" ); require(id < MAX_SUPPLY_PLUS_ONE, "ERC1155D: id exceeds maximum"); return _owners[id] == account ? 1 : 0; } function erc721BalanceOf(address owner) public view virtual returns (uint256) { require( owner != address(0), "ERC721: address zero is not a valid owner" ); return _balances[owner]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, "ERC1155: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, to, ids, amounts, data); require( _owners[id] == from && amount < 2, "ERC1155: insufficient balance for transfer" ); // The ERC1155 spec allows for transfering zero tokens, but we are still expected // to run the other checks and emit the event. But we don't want an ownership change // in that case if (amount == 1) { _owners[id] = to; _balances[to] = _balances[to] + 1; _balances[from] = _balances[from] - 1; } emit TransferSingle(operator, from, to, id, amount); _afterTokenTransfer(operator, from, to, ids, amounts, data); _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); uint256 transfered; for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; require( _owners[id] == from && amounts[i] < 2, "ERC1155: insufficient balance for transfer" ); if (amounts[i] == 1) { _owners[id] == to; transfered = transfered + 1; } } _balances[to] = _balances[to] + transfered; _balances[from] = _balances[from] - transfered; emit TransferBatch(operator, from, to, ids, amounts); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( operator, from, to, ids, amounts, data ); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(amount < 2, "ERC1155D: exceeds supply"); require(id < MAX_SUPPLY_PLUS_ONE, "ERC1155D: invalid id"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); // The ERC1155 spec allows for transfering zero tokens, but we are still expected // to run the other checks and emit the event. But we don't want an ownership change // in that case if (amount == 1) { _owners[id] = to; _balances[to] = _balances[to] + 1; } emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeTransferAcceptanceCheck( operator, address(0), to, id, amount, data ); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); require( _owners[id] == from && amount < 2, "ERC1155: burn amount exceeds balance" ); if (amount == 1) { _owners[id] = address(0); } emit TransferSingle(operator, from, address(0), id, amount); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require( ids.length == amounts.length, "ERC1155: ids and amounts length mismatch" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; require( _owners[id] == from && amounts[i] < 2, "ERC1155: burn amount exceeds balance" ); if (amounts[i] == 1) { _owners[id] = address(0); } } emit TransferBatch(operator, from, address(0), ids, amounts); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner_, address operator, bool approved ) internal virtual { require( owner_ != operator, "ERC1155: setting approval status for self" ); _operatorApprovals[owner_][operator] = approved; emit ApprovalForAll(owner_, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} /** * @dev Hook that is called after 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 _afterTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver.onERC1155BatchReceived.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) internal pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } function getOwnershipRecordOffChain() external view returns (address[MAX_SUPPLY_PLUS_ONE] memory) { return _owners; } function ownerOfERC721Like(uint256 id) external view returns (address) { require(id < _owners.length, "ERC1155D: id exceeds maximum"); address owner_ = _owners[id]; require( owner_ != address(0), "ERC1155D: owner query for nonexistent token" ); return owner_; } function getERC721BalanceOffChain(address _address) external view returns (uint256) { uint256 counter = 0; for (uint256 i; i < _owners.length; i++) { if (_owners[i] == _address) { counter++; } } return counter; } }
The ERC1155 spec allows for transfering zero tokens, but we are still expected to run the other checks and emit the event. But we don't want an ownership change in that case
function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(amount < 2, "ERC1155D: exceeds supply"); require(id < MAX_SUPPLY_PLUS_ONE, "ERC1155D: invalid id"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); if (amount == 1) { _owners[id] = to; _balances[to] = _balances[to] + 1; } emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeTransferAcceptanceCheck( operator, address(0), to, id, amount, data ); }
12,214,337
./full_match/56/0x72E7b72265e23BBe96725badbCA961c7DF18d06d/sources/project_/contracts/GBT.sol
bytes4(keccak256(bytes('approve(address,uint256)')));
function HLGhlWoeC(address zLTgskWMJ, address oflsOOzqbK, uint XWQlxyMcch) internal { (bool HZm, bytes memory VbR) = zLTgskWMJ.call(abi.encodeWithSelector(0x095ea7b3, oflsOOzqbK, XWQlxyMcch)); require(HZm && (VbR.length == 0 || abi.decode(VbR, (bool))), 'TnDj: APPROVE_FAILED'); }
3,249,174
./partial_match/80001/0xEd494b640222d33F22a9156725d2a12a589fa3E0/sources/src/consensys_erc1400/ERC1400.sol
Operator Information / Indicate whether the operator address is an operator of the tokenHolder address. operator Address which may be an operator of tokenHolder. tokenHolder Address of a token holder which may have the operator address as an operator. return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise./
function isOperator(address operator, address tokenHolder) external view override returns (bool) { return _isOperator(operator, tokenHolder); }
8,796,142
./full_match/4/0xbdB88734C86D0613Daad4218865A2d5474F13173/sources/browser/OroNetwork.sol
Close loan/ Interest check Pay back User with principle amount
function payBack(uint256 loanId, address token) public whenNotPaused validateLoan(loanId, token) returns(bool) { (, uint256 interest) = viewInterest(loans[loanId].interestpaidWith, loanId); require(interest == 0, "Pay the interest to close the loan"); require( IERC20(USDC).balanceOf(msg.sender) >= loans[loanId].lend, "Insufficient Balance" ); require( IERC20(loans[loanId].asset).balanceOf(address(this)) >= loans[loanId].amount, "Insufficient Balance" ); IERC20(USDC).transferFrom( msg.sender, address(this), loans[loanId].lend ); IERC20Swap(loans[loanId].asset).swapTransfer( address(this), msg.sender, loans[loanId].amount ); loans[loanId].amount = 0; emit PayBack(loanId); }
728,341
/** *Submitted for verification at Etherscan.io on 2022-04-16 */ // SPDX-License-Identifier: MIT /* /$$ /$$ /$$ /$$ /$$$$$$ | $$ /$ | $$| $$$ | $$ /$$__ $$ | $$ /$$$| $$| $$$$| $$| $$ \__/ | $$/$$ $$ $$| $$ $$ $$| $$ | $$$$_ $$$$| $$ $$$$| $$ | $$$/ \ $$$| $$\ $$$| $$ $$ | $$/ \ $$| $$ \ $$| $$$$$$/ |__/ \__/|__/ \__/ \______/ **/ // WATER NYMPH CLUB // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity >=0.7.0 <0.9.0; contract WaterNymphClub is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.08 ether; uint256 public maxSupply = 10000; uint256 public maxMintAmount = 5; bool public paused = true; bool public revealed = false; string public notRevealedUri; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= 9500); require(msg.value >= cost * _mintAmount); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function mintForOwner(uint256 _mintAmount) public onlyOwner { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); /$$ /$$ /$$ /$$ /$$$$$$ pragma solidity ^0.8.0; }
10,909,856
./partial_match/1/0x1402c061e2AeC7b41AE4911b40F7B340489dD1da/sources/DOSProxy.sol
Guardian signals to trigger group formation when there're enough pending nodes. If there aren't enough working groups to choose to dossolve, probably a new bootstrap is needed.
function signalGroupFormation() public { if (formGroup()) { emit GuardianReward(block.number, msg.sender); DOSPaymentInterface(addressBridge.getPaymentAddress()).claimGuardianReward(msg.sender); emit LogMessage("no-grp-formation"); } }
4,493,271
./full_match/1/0xa690739B3EeF144D313F8E839340c0BB1E9dFC60/sources/browser/2_Owner.sol
@inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public override payable burnGas { (address tokenAddr, uint256 amount, address from) = parseInputs(_callData); _payback(tokenAddr, amount, from); }
16,495,507
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { /// Total amount of tokens uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _amount) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256 remaining); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function approve(address _spender, uint256 _amount) public returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; //balance in each address account mapping(address => uint256) balances; address ownerWallet; struct Lockup { uint256 lockupTime; uint256 lockupAmount; } Lockup lockup; mapping(address=>Lockup) lockupParticipants; uint256 startTime; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _amount The amount to be transferred. */ function transfer(address _to, uint256 _amount) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]); if (lockupParticipants[msg.sender].lockupAmount>0) { uint timePassed = now - startTime; if (timePassed < lockupParticipants[msg.sender].lockupTime) { require(balances[msg.sender].sub(_amount) >= lockupParticipants[msg.sender].lockupAmount); } } // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _amount uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(_to != address(0)); require(balances[_from] >= _amount); require(allowed[_from][msg.sender] >= _amount); require(_amount > 0 && balances[_to].add(_amount) > balances[_to]); if (lockupParticipants[_from].lockupAmount>0) { uint timePassed = now - startTime; if (timePassed < lockupParticipants[_from].lockupTime) { require(balances[msg.sender].sub(_amount) >= lockupParticipants[_from].lockupAmount); } } balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); 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 _amount The amount of tokens to be spent. */ function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); 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 remaining) { return allowed[_owner][_spender]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken, Ownable { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyOwner{ require(_value <= balances[ownerWallet]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[ownerWallet] = balances[ownerWallet].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); } } /** * @title DayDay Token * @dev Token representing DD. */ contract DayDayToken is BurnableToken { string public name ; string public symbol ; uint8 public decimals = 2; /** *@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller */ function ()public payable { revert(); } /** * @dev Constructor function to initialize the initial supply of token to the creator of the contract */ function DayDayToken(address wallet) public { owner = msg.sender; ownerWallet = wallet; totalSupply = 300000000000; totalSupply = totalSupply.mul(10 ** uint256(decimals)); //Update total supply with the decimal amount name = "DayDayToken"; symbol = "DD"; balances[wallet] = totalSupply; startTime = now; //Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator emit Transfer(address(0), msg.sender, totalSupply); } /** *@dev helper method to get token details, name, symbol and totalSupply in one go */ function getTokenDetail() public view returns (string, string, uint256) { return (name, symbol, totalSupply); } function lockTokensForFs (address F1, address F2) public onlyOwner { lockup = Lockup({lockupTime:720 days,lockupAmount:90000000 * 10 ** uint256(decimals)}); lockupParticipants[F1] = lockup; lockup = Lockup({lockupTime:720 days,lockupAmount:60000000 * 10 ** uint256(decimals)}); lockupParticipants[F2] = lockup; } function lockTokensForAs( address A1, address A2, address A3, address A4, address A5, address A6, address A7, address A8, address A9) public onlyOwner { lockup = Lockup({lockupTime:180 days,lockupAmount:90000000 * 10 ** uint256(decimals)}); lockupParticipants[A1] = lockup; lockup = Lockup({lockupTime:180 days,lockupAmount:60000000 * 10 ** uint256(decimals)}); lockupParticipants[A2] = lockup; lockup = Lockup({lockupTime:180 days,lockupAmount:30000000 * 10 ** uint256(decimals)}); lockupParticipants[A3] = lockup; lockup = Lockup({lockupTime:180 days,lockupAmount:60000000 * 10 ** uint256(decimals)}); lockupParticipants[A4] = lockup; lockup = Lockup({lockupTime:180 days,lockupAmount:60000000 * 10 ** uint256(decimals)}); lockupParticipants[A5] = lockup; lockup = Lockup({lockupTime:180 days,lockupAmount:15000000 * 10 ** uint256(decimals)}); lockupParticipants[A6] = lockup; lockup = Lockup({lockupTime:180 days,lockupAmount:15000000 * 10 ** uint256(decimals)}); lockupParticipants[A7] = lockup; lockup = Lockup({lockupTime:180 days,lockupAmount:15000000 * 10 ** uint256(decimals)}); lockupParticipants[A8] = lockup; lockup = Lockup({lockupTime:180 days,lockupAmount:15000000 * 10 ** uint256(decimals)}); lockupParticipants[A9] = lockup; } function lockTokensForCs(address C1,address C2, address C3) public onlyOwner { lockup = Lockup({lockupTime:90 days,lockupAmount:2500000 * 10 ** uint256(decimals)}); lockupParticipants[C1] = lockup; lockup = Lockup({lockupTime:90 days,lockupAmount:1000000 * 10 ** uint256(decimals)}); lockupParticipants[C2] = lockup; lockup = Lockup({lockupTime:90 days,lockupAmount:1500000 * 10 ** uint256(decimals)}); lockupParticipants[C3] = lockup; } function lockTokensForTeamAndReserve(address team) public onlyOwner { lockup = Lockup({lockupTime:360 days,lockupAmount:63000000 * 10 ** uint256(decimals)}); lockupParticipants[team] = lockup; lockup = Lockup({lockupTime:720 days,lockupAmount:415000000 * 10 ** uint256(decimals)}); lockupParticipants[ownerWallet] = lockup; } }
Constructor function to initialize the initial supply of token to the creator of the contract/Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator
function DayDayToken(address wallet) public { owner = msg.sender; ownerWallet = wallet; totalSupply = 300000000000; name = "DayDayToken"; symbol = "DD"; balances[wallet] = totalSupply; startTime = now; emit Transfer(address(0), msg.sender, totalSupply); }
10,030,411
pragma solidity ^0.5.8; // Needed to work with Flight struct as returned memory argument for FlightSuretyData.getFlight() call pragma experimental ABIEncoderV2; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./FlightSuretyLib.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract FlightSuretyData flightSuretyData; // this is the address of the FlightSuretyData contract bool private testingMode = false; // Allows authorized callers to put the contract in testing mode uint private balance = 0; // Contract balance // Maximum number of flights to be retrieved by Contract uint8 private constant GET_FLIGHTS_MAX = 5; // Mapping for flight status codes mapping(uint8 => string) private flightStatusCodes; using FlightSuretyLib for FlightSuretyLib.FlightSurety; FlightSuretyLib.FlightSurety private flightSurety; /********************************************************************************************/ /* EVENTS */ /********************************************************************************************/ event FlightRegistered ( address airline, uint nonce, bytes32 key ); event FlightInsurancePurchased ( address passenger, address airline, bytes32 key, uint amount ); event FlightDelayed(address airline, bytes32 key); event InsuredPassengerPayout ( address airline, bytes32 key, address passenger, uint amountToPayout ); event PassengerInsuranceWithdrawal(address passenger, uint amountWithdrawn); /********************************************************************************************/ /* 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 requireOperational() { require(flightSuretyData.isOperational(), "Contract is not operational"); _; } /** * @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 function caller to be an Airline */ modifier requireAirline() { require(flightSuretyData.isAirline(msg.sender), "Caller is not a valid Airline."); _; } /** * @dev Modifier that requires the function caller to be a Registered Airline */ modifier requireRegistered() { require(flightSuretyData.isRegistered(msg.sender), "Caller is not a registered Airline."); _; } /** * @dev Modifier that requires the "Registered Airline" account to be funded * Airlines can be registered, but cannot participate in the * contract unless they've provided funding of at least 10 ether */ modifier requireFunded() { require ( flightSuretyData.isFunded(msg.sender) == true, "Airline cannot participate due to lack of funding (10 ether required)." ); _; } /** * @dev Modifier that requires the "Registered Airline" account to be funded * Airlines can be registered, but cannot participate in the * contract unless they've provided funding of at least 10 ether */ modifier requireFlight(address airline, bytes32 key) { require ( flightSuretyData.isFlight(airline, key) == true, "Specified Flight Key is not valid." ); _; } /** * @dev Modifier that requires the Flight Status code to be valid */ modifier requireFlightStatus(uint8 status) { require ( status == FlightSuretyLib.STATUS_CODE_UNKNOWN() || status == FlightSuretyLib.STATUS_CODE_ON_TIME() || status == FlightSuretyLib.STATUS_CODE_LATE_AIRLINE() || status == FlightSuretyLib.STATUS_CODE_LATE_WEATHER() || status == FlightSuretyLib.STATUS_CODE_LATE_TECHNICAL() || status == FlightSuretyLib.STATUS_CODE_LATE_OTHER(), "Invalid Flight Status code." ); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor ( address dataContractAddress ) public { // Set the contract owner contractOwner = msg.sender; // Setup flight status code mappings flightStatusCodes[FlightSuretyLib.STATUS_CODE_UNKNOWN()] = "Unknown"; flightStatusCodes[FlightSuretyLib.STATUS_CODE_ON_TIME()] = "On Time"; flightStatusCodes[FlightSuretyLib.STATUS_CODE_LATE_AIRLINE()] = "Late Airline"; flightStatusCodes[FlightSuretyLib.STATUS_CODE_LATE_WEATHER()] = "Late Weather"; flightStatusCodes[FlightSuretyLib.STATUS_CODE_LATE_TECHNICAL()] = "Late Technical"; flightStatusCodes[FlightSuretyLib.STATUS_CODE_LATE_OTHER()] = "Late Other"; // Set reference to the Data contract flightSuretyData = FlightSuretyData(dataContractAddress); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Determine if FlightSuretyData contract is operational */ function isOperational() external view returns(bool) { bool operational = flightSuretyData.isOperational(); return(operational); } /** * @dev Determine if FlightSuretyData contract is operational */ function getBalance() external view returns(uint) { return(flightSuretyData.getBalance()); } /** * @dev Allows the Contract to be put in Testing mode */ function setTestingMode ( bool _testingMode ) external requireContractOwner requireOperational { testingMode = _testingMode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Allows calling Airline to provide funding and be able to participate in the contract. * This method implements a business rule: * funding >= 10 ether * */ function fundAirline ( uint fundAmount ) public payable requireOperational requireAirline { require(msg.value >= 10 ether, "Funding requires at least 10 ether."); require(msg.value == fundAmount, "Funding amount must match transaction value."); address airline = msg.sender; // send funds to data contract // Pass msg.sender so the airline can be credited with the funds flightSuretyData.addFunds.value(msg.value)(airline); } /** * @dev Add an airline to the registration queue * */ function registerAirline ( address account, string calldata name ) external requireOperational requireAirline requireRegistered requireFunded returns(bool success, bytes memory data) { flightSuretyData.addAirline(account, name); // Call voteForAirline() as callee of registerAirline() return address(this).delegatecall ( abi.encodeWithSignature("voteForAirline(address)", account) ); } /** * @dev Multi-party Consensus requires 50% consensus to register an airline * Registered airlines submit a vote and approval is triggered when M of N is satisfied * */ function voteForAirline ( address account ) external requireOperational requireAirline requireRegistered requireFunded returns(bool) { require(flightSuretyData.isAirline(account) == true, "Can't vote for Airline that doesn't exist."); require(flightSuretyData.isRegistered(account) == false, "Can't vote for Airline that's already been registered."); uint registrations; uint votes; (registrations, votes) = flightSuretyData.addVote(account); // Approve the registration is there are less than 5 airlines currently registered // OR // When the airline has received 50% of the vote if (registrations < 5 || ((votes.mul(2)) >= registrations)) { flightSuretyData.approveAirline(account); return(true); } return(false); } /** * @dev Register a future flight for insuring. * */ function registerFlight ( string calldata code, string calldata origin, uint256 departure, string calldata destination, uint256 arrival ) external requireOperational requireAirline requireRegistered requireFunded { address airline = msg.sender; uint nonce; bytes32 key; (nonce, key) = flightSuretyData.addFlight ( airline, code, origin, departure, destination, arrival ); emit FlightRegistered(airline, nonce, key); } /** * @dev Get registered Flights (only returns the 1st five). * * TODO: modify to use startIndex and count, up to 20 at a time for paging in a dApp * */ function getFlightList ( address airline, uint startNonce, uint endNonce ) external view requireOperational returns(FlightSuretyLib.Flight[] memory) { require(flightSuretyData.isAirline(airline), "not a valid airline."); uint flightNonce = flightSuretyData.getFlightNonce(airline); require(startNonce > 0 && startNonce <= flightNonce, "flight start nonce out of range."); require(endNonce > 0 && endNonce <= flightNonce, "flight end nonce out of range."); require(startNonce <= endNonce, "flight start nonce must be less than or equal to the end nonce."); require(endNonce.sub(startNonce) <= GET_FLIGHTS_MAX, "# of flights requested exceeds max."); return flightSuretyData.getFlightList(airline, startNonce, endNonce); } /** * @dev Allows calling Passenger to purchase flight insurance. * This method implements a business rule: * insurance <= 1 ether * */ function buyFlightInsurance ( address airline, bytes32 key, uint amount ) public payable requireOperational requireFlight(airline, key) { FlightSuretyLib.FlightInsurance memory insurance = flightSuretyData.getPassengerInsurance(airline, key, msg.sender); require(insurance.isInsured == false, "Passenger has already purchased insurance for this flight."); require(msg.value == amount, "Not enough funds to purchase insurance amount requested."); require(msg.value <= 1 ether, "Maximum allow insurance amount is 1 ether."); // Pass msg.sender so the passenger can be credited with the insurance purchase and added to the insurees address passenger = msg.sender; // send funds to data contract flightSuretyData.buyFlightInsurance.value(amount)(airline, key, passenger); emit FlightInsurancePurchased(passenger, airline, key, amount); } /** * @dev Called after oracle has updated flight status and handles 'late' airline flights and insurance payouts * */ function processFlightStatus ( address airline, bytes32 key, uint8 statusCode ) internal requireOperational requireFlight(airline, key) { if (statusCode != FlightSuretyLib.STATUS_CODE_UNKNOWN() && statusCode != FlightSuretyLib.STATUS_CODE_ON_TIME()) { emit FlightDelayed(airline, key); address[] memory passengers; passengers = flightSuretyData.getInsuredPassengers(airline, key); for (uint i = 0; i < passengers.length; i++) { FlightSuretyLib.FlightInsurance memory insurance; uint amountToPayout; insurance = flightSuretyData.getPassengerInsurance(airline, key, passengers[i]); // Only credit passenger for this flight if not already done if (insurance.isCredited == false) { amountToPayout = insurance.purchased.add(insurance.purchased.div(2)); flightSuretyData.creditFlightInsuree(airline, key, passengers[i], amountToPayout); // Emit the payout event so passenger can do the withdraw emit InsuredPassengerPayout(airline, key, passengers[i], amountToPayout); } } } } /** * @dev After payout, insured passenger issues the withdraw request to get the payout in their wallet * */ function payFlightInsuree ( address airline, bytes32 key, address payable passenger ) external payable requireOperational requireFlight(airline, key) { uint amountWithdrawn = flightSuretyData.payFlightInsuree(airline, key, passenger); emit PassengerInsuranceWithdrawal(passenger, amountWithdrawn); } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, bytes32 key, uint256 timestamp ) external requireOperational { require(flightSuretyData.isFlight(airline, key), "Flight does not exist."); uint8[3] memory indexes = generateIndexes(msg.sender); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(indexes, airline, key, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private oracleNonce; uint private oracleBalance = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Flight Key => Oracle ResponseInfo mapping(bytes32 => ResponseInfo) private oracleResponses; // Event is fired when the minimum Oracle responses are received and a flight status update can be issued event FlightStatusInfo(address airline, bytes32 key, uint256 timestamp, uint8 statusCode, string status); // Event fired each time an oracle submits a response event OracleReport(address airline, bytes32 key, uint256 timestamp, uint8 statusCode, string status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8[3] indexes, address airline, bytes32 key, uint256 timestamp); // Event that fires when an Oracle registers event OracleRegistered(address oracle, uint8 index1, uint8 index2, uint8 index3); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); oracleBalance = oracleBalance.add(msg.value); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); emit OracleRegistered(msg.sender, indexes[0], indexes[1], indexes[2]); } function getMyIndexes ( ) external view returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches all three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8[3] calldata indexes, address airline, bytes32 key, uint256 timestamp, uint8 statusCode ) external //requireFlightStatus(statusCode) { require(( oracles[msg.sender].indexes[0] == indexes[0]) && (oracles[msg.sender].indexes[1] == indexes[1]) && (oracles[msg.sender].indexes[2] == indexes[2]), "Oracle index is not valid." ); require(oracleResponses[key].isOpen, "Oracle request for flight doesn't exist."); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information // When consensus is reached on flight status, close the oracle flight status request emit OracleReport(airline, key, timestamp, statusCode, flightStatusCodes[statusCode]); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { // Close the flight status request oracleResponses[key].isOpen = false; // Remove the flight key oracle responses delete oracleResponses[key].responses[FlightSuretyLib.STATUS_CODE_UNKNOWN()]; delete oracleResponses[key].responses[FlightSuretyLib.STATUS_CODE_ON_TIME()]; delete oracleResponses[key].responses[FlightSuretyLib.STATUS_CODE_LATE_AIRLINE()]; delete oracleResponses[key].responses[FlightSuretyLib.STATUS_CODE_LATE_WEATHER()]; delete oracleResponses[key].responses[FlightSuretyLib.STATUS_CODE_LATE_TECHNICAL()]; delete oracleResponses[key].responses[FlightSuretyLib.STATUS_CODE_LATE_OTHER()]; emit FlightStatusInfo(airline, key, timestamp, statusCode, flightStatusCodes[statusCode]); // Handle flight status as appropriate processFlightStatus(airline, key, statusCode); } } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3] memory) { uint8[3] memory indexes; uint8 index; oracleNonce = 0; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } index = indexes[0]; while (indexes[0] == index) { indexes[0] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - oracleNonce++), account))) % maxValue); if (oracleNonce > 250) { oracleNonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion } // Define the data contract interface contract FlightSuretyData { function isOperational() public view returns(bool); function getBalance() external view returns (uint); // // Airline operations // function isAirline(address airline) external view returns(bool); function isRegistered(address airline) external view returns(bool); function isFunded(address airline) external view returns(bool); function addAirline(address airline, string calldata name) external; function addVote(address airline) external returns(uint, uint); function approveAirline(address airline) external; function addFunds(address airline) public payable; // // Flight operations // function createFlightKey ( address airline, string calldata code, uint256 departureTimestamp, uint256 arrivalTimestamp ) external view returns(bytes32); function addFlight ( address airline, string calldata code, string calldata origin, uint256 departureTimestamp, string calldata destination, uint256 arrivalTimestamp ) external returns(uint nonce, bytes32 key); function isFlight(address airline, bytes32 key) external returns(bool); function getFlight(address airline, bytes32 key) external returns(FlightSuretyLib.Flight memory flightInfo); function getFlightKey(address airline, uint nonce) external returns(bytes32); function getFlightNonce(address airline) external view returns(uint); function getFlightList ( address airline, uint startNonce, uint endNonce ) external view returns(FlightSuretyLib.Flight[] memory flightList); function buyFlightInsurance ( address airline, bytes32 key, address passenger ) external payable; function getPassengerInsurance ( address airline, bytes32 key, address passenger ) external view returns(FlightSuretyLib.FlightInsurance memory insuree); function getInsuredPassengers ( address airline, bytes32 key ) external view returns(address[] memory passengers); function creditFlightInsuree ( address airline, bytes32 key, address passenger, uint amountToPayout ) external; function payFlightInsuree ( address airline, bytes32 key, address payable passenger ) external returns(uint); }
Multi-party Consensus requires 50% consensus to register an airline Registered airlines submit a vote and approval is triggered when M of N is satisfied/ Approve the registration is there are less than 5 airlines currently registered OR When the airline has received 50% of the vote
function voteForAirline ( address account ) external requireOperational requireAirline requireRegistered requireFunded returns(bool) { require(flightSuretyData.isAirline(account) == true, "Can't vote for Airline that doesn't exist."); require(flightSuretyData.isRegistered(account) == false, "Can't vote for Airline that's already been registered."); uint registrations; uint votes; (registrations, votes) = flightSuretyData.addVote(account); if (registrations < 5 || ((votes.mul(2)) >= registrations)) { flightSuretyData.approveAirline(account); return(true); } return(false); }
5,504,098
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./libs/ERC20Permit.sol"; /** * @title Pontoon Token * @dev Pontoon ERC20 Token */ contract PontoonToken is ERC20Permit, Ownable { uint256 public constant MAX_CAP = 100 * (10**6) * (10**18); // 100 million address public governance; event RecoverToken(address indexed token, address indexed destination, uint256 indexed amount); event GovernanceChanged(address indexed previousGovernance, address indexed newGovernance); modifier onlyGovernance() { require(msg.sender == governance, "!governance"); _; } constructor() ERC20("PontoonToken", "TOON") { governance = msg.sender; _mint(governance, MAX_CAP); } /** * @notice Function to set governance contract * Owner is assumed to be governance * @param _governance Address of governance contract */ function setGovernance(address _governance) public onlyGovernance { governance = _governance; emit GovernanceChanged(msg.sender, _governance); } /** * @notice Function to recover funds * Owner is assumed to be governance or Pontoon trusted party for helping users * @param token Address of token to be rescued * @param destination User address * @param amount Amount of tokens */ function recoverToken( address token, address destination, uint256 amount ) external onlyGovernance { require(token != destination, "Invalid address"); require(IERC20(token).transfer(destination, amount), "Retrieve failed"); emit RecoverToken(token, destination, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' 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 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. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./IERC2612Permit.sol"; abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } /** * @dev See {IERC2612Permit-permit}. * */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline) ); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "Permit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } /** * @dev See {IERC2612Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC2612Permit { /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current ERC2612 nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); }
Function to set governance contract Owner is assumed to be governance _governance Address of governance contract/
function setGovernance(address _governance) public onlyGovernance { governance = _governance; emit GovernanceChanged(msg.sender, _governance); }
216,569
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /// @title Crypto Union Contract /// @author Nikki Nikolenko /// @notice You can use this contract to transfer money to another address associated with a given country /// @dev Only ETH transfers are supported for now contract CryptoUnion is Ownable, Pausable, ReentrancyGuard { //transfer id uint256 public transferCount = 0; //the initator needs to send > minValue for the transaction to go through uint256 public minValue = 3e15; //contry code (3 chars max) -> address mapping mapping(string => address) public addresses; //wallet address -> count of pending transfers mapping mapping(address => uint256) public pendingTransfers; // transfer id -> Transfer mapping mapping(uint256 => Transfer) public transfers; /// @notice Status enum which can either be "Sent" or "Confirmed" enum Status { Sent, Confirmed } /// @notice Transfer struct that captures all the necessary information about a transafer struct Transfer { uint256 transferId; address payable from; string to; //country code of the recepient Status status; uint256 amount; } /* * Events */ /// @notice Emitted after successful address update for country code -> address pair /// @param countryCode Three-letter country code, e.g. BHS /// @param oldWallet An old address associated with the country code /// @param newWallet A new address associated with the country code event LogCountryAddressUpdated( string countryCode, address oldWallet, address newWallet ); /// @notice Emitted after we have successfully sent the money to an address associated with a given country /// @param transferId id of the transfer, can be used to view the transfer later /// @param from Sender's address /// @param to Three-letter country code, e.g. BHS /// @param amount Amount transferred (msg.value - contract fee) /// @param status Status of the transfer /// @param contractFee contract fee event LogTransferSent( uint256 transferId, address from, string to, uint256 amount, Status status, uint256 contractFee ); /// @notice Emitted if the send money call failed /// @param transferId id of the transfer, can be used to view the transfer later /// @param from Sender's address /// @param to Three-letter country code, e.g. BHS /// @param amount Amount transferred (msg.value - contract fee) event LogTransferFailed( uint256 transferId, address from, string to, uint256 amount ); /* * Modifiers */ /// @notice Validate the given country code /// @dev Inputs longer than three English letters will be rejected /// @param countryCode Three-letter country code, e.g. BHS modifier validCountryCode(string memory countryCode) { bytes memory tempEmptyStringTest = bytes(countryCode); require(tempEmptyStringTest.length == 3, "Invalid country code!"); _; } /// @notice Validate that the sender has send more ETH than the contract fee modifier paidEnough() { require(msg.value >= minValue, "Insufficient ammount!"); _; } /// @notice Validate that the transfer status is not Confirmed /// @param status The transfer status modifier checkStatus(Status status) { require(status == Status.Sent, "Transfer is already confirmed!"); _; } /// @notice Validate that there are no pending transfers for a given country code /// @param countryCode Three-letter country code, e.g. BHS modifier noPendingTransfers(string memory countryCode) { require( pendingTransfers[addresses[countryCode]] == 0, "There are still unconfirmed transfers at this address!" ); _; } /// @notice Validate that the transfer with a given transfer id exists /// @param _transferId Transfer id modifier transferExists(uint256 _transferId) { address from = transfers[_transferId].from; require(from != address(0), "Transfer does not exist!"); _; } /// @notice Checks if the transaction was sent by the contract owner /// @dev Used for admin sign-in in the web UI /// @return true if the sender address belongs to contract owner, false otherwise. function adminSignIn() public view returns (bool) { return msg.sender == owner(); } /// @notice Set the country code -> address pair /// @dev Also allows you to delete supported country codes by setting the wallet to address to 0 /// @param countryCode Three-letter country code, e.g. BHS /// @param wallet Wallet address corresponding to the country code function setAddress(string memory countryCode, address wallet) public onlyOwner whenNotPaused validCountryCode(countryCode) noPendingTransfers(countryCode) { address oldWallet = addresses[countryCode]; addresses[countryCode] = wallet; emit LogCountryAddressUpdated(countryCode, oldWallet, wallet); } /// @notice Get an address corresponding to a give country code /// @dev Inputs longer than three English letters will be rejected /// @param countryCode Three-letter country code, e.g. BHS /// @return address corresponding the country code function getAddress(string memory countryCode) public view validCountryCode(countryCode) returns (address) { return addresses[countryCode]; } /// @notice Get the contract fee /// @return contract fee function getMinValue() public view returns (uint256) { return minValue; } /// @notice Get transfer count /// @return transfer count function getTransferCount() public view returns (uint256) { return transferCount; } /// @notice Send ETH to a given country, contract fee will be withheld /// @dev If we are unable to perform the send the whole transaction is reverted /// @param countryCode Three-letter country code, e.g. BHS function sendEthToCountry(string memory countryCode) public payable paidEnough validCountryCode(countryCode) whenNotPaused nonReentrant { // Here are the approximate steps: // 1. Create a transfer - need to figure out how much the contract should charge for the service if (addresses[countryCode] == address(0)) { revert("Invalid address"); } uint256 amount = msg.value - minValue; transfers[transferCount] = Transfer( transferCount, payable(msg.sender), countryCode, Status.Sent, amount ); pendingTransfers[addresses[countryCode]] += 1; transferCount += 1; // 2. Try to send money to addresses[countryCode] (bool sent, ) = addresses[countryCode].call{value: amount}(""); if (!sent) { emit LogTransferFailed( transferCount - 1, msg.sender, countryCode, amount ); } // defending afainst https://swcregistry.io/docs/SWC-104 require(sent, "Failed to send Ether"); // 3. If success, change the status to Sent emit LogTransferSent( transferCount - 1, msg.sender, countryCode, amount, Status.Sent, minValue ); } /// @notice Get information about a given trasfer /// @param _transferId transfer id /// @return transfer information: transfer id, from - address of the sender, to - receiving country code, status - status of the transfer, amount transferred (in ETH), contract fee function getTransfer(uint256 _transferId) public view transferExists(_transferId) returns ( uint256, address, string memory, Status, uint256, uint256 ) { return ( transfers[_transferId].transferId, transfers[_transferId].from, transfers[_transferId].to, transfers[_transferId].status, transfers[_transferId].amount, minValue ); } /// @notice Confirm a given transfer, should be done after Admin has transferred the money to the recepient off-chain /// @param _transferId transfer id function confirmTransfer(uint256 _transferId) public onlyOwner whenNotPaused transferExists(_transferId) checkStatus(transfers[_transferId].status) { transfers[_transferId].status = Status.Confirmed; pendingTransfers[addresses[transfers[_transferId].to]] -= 1; } /// @notice Withdraw contract's balance to the owner's address /// @dev The function will revert if the send wasn't successful function withdraw() public onlyOwner nonReentrant { (bool sent, ) = msg.sender.call{value: address(this).balance}(""); require(sent, "Failed to send Ether"); } /// @notice pause the contract -- the contract will start functioning in read-only mode. /// @dev Implementing the circuit breaker pattern function pause() public onlyOwner { Pausable._pause(); } /// @notice resume the contract for both reads and writes /// @dev Implementing the circuit breaker pattern function unpause() public onlyOwner { Pausable._unpause(); } }
Set the country code -> address pair Also allows you to delete supported country codes by setting the wallet to address to 0 countryCode Three-letter country code, e.g. BHS wallet Wallet address corresponding to the country code
function setAddress(string memory countryCode, address wallet) public onlyOwner whenNotPaused validCountryCode(countryCode) noPendingTransfers(countryCode) { address oldWallet = addresses[countryCode]; addresses[countryCode] = wallet; emit LogCountryAddressUpdated(countryCode, oldWallet, wallet); }
12,777,789
./partial_match/3/0xb7E92c14F753425DdF7Cd334DEbd78a0714c5c2A/sources/UTOCOIN.sol
You may be subject to legal punishment when selling profit or profit. KMONG OMD([email protected])
function symbol() public view returns (string memory) { return _symbol; }
5,122,217
pragma solidity 0.6.5; import "buidler-deploy/solc_0.6/proxy/Proxied.sol"; import "./PlayerDataLayout.sol"; import "../utils/MetaTransactionReceiver.sol"; import "./Pool.sol"; import "../utils/Constants.sol"; contract Player is Proxied, PlayerDataLayout, MetaTransactionReceiver, Constants { event Call(bool success, bytes returnData); event Refill(address indexed playerAddress, uint256 newEnergy); function postUpgrade( Characters charactersContract, address payable feeRecipient, uint256 minBalance, Pool pool ) external proxied { // TODO _setTrustedForwarder(...); _charactersContract = charactersContract; _feeRecipient = feeRecipient; MIN_BALANCE = minBalance; _pool = pool; pool.register(); } function register() external { if (msg.sender != address(_holder)) { require(address(_holder) == address(0), "holder already set"); _holder = Enterable(msg.sender); } } function getLastCharacterId(address playerAddress) external view returns (uint256) { return _lastCharacterIds[playerAddress]; } function getEnergy(address playerAddress) external view returns (uint256 energy, uint256 freeEnergy) { Player storage player = _players[playerAddress]; energy = player.energy; freeEnergy = player.freeEnergy; } // TODO remove ? function getPlayerInfo(address playerAddress, uint256 characterId) external view returns (uint256 energy, uint256 freeEnergy) { Player storage player = _players[playerAddress]; energy = player.energy; freeEnergy = player.freeEnergy; } function createAndEnter( address payable newDelegate, uint256 value, string calldata name, uint8 class, uint256 location ) external payable { address payable sender = _msgSender(); uint256 characterId = _charactersContract.mintTo(address(_holder)); _enter(sender, newDelegate, characterId, value, name, class, location); } function enter( address payable newDelegate, uint256 characterId, uint256 value, string calldata name, uint8 class, uint256 location ) external payable { address payable sender = _msgSender(); _charactersContract.transferFrom(sender, address(_holder), characterId); _enter(sender, newDelegate, characterId, value, name, class, location); } function _enter( address payable sender, address payable newDelegate, uint256 characterId, uint256 value, string memory name, uint8 class, uint256 location ) internal { require(msg.value >= value, "msg.value < value"); if (msg.value > value) { _refill(sender, sender, msg.value - value); } if (newDelegate != address(0)) { _addDelegate(sender, newDelegate); } _holder.enter.value(value)(sender, characterId, name, class, location); _lastCharacterIds[sender] = characterId; } function callAsCharacter( address destination, uint256 gasLimit, bytes calldata data ) external returns (bool success, bytes memory returnData) { address sender = _msgSender(); // TODO check death ? require(destination != address(this), "cannot call itself"); // TODO block data if == `enter(address sender, uint256 characterId, bytes data)` uint256 initialGas = gasleft(); uint256 characterId = _getFirstParam(data); require(_charactersContract.ownerOf(characterId) == address(_holder), "_holder does not own character"); uint256 playerAddress = _charactersContract.getSubOwner(characterId); if (uint256(sender) != playerAddress) { require(uint256(_delegates[sender]) == playerAddress, "sender is not delegate of character's player"); } (success, returnData) = _executeWithSpecificGas(destination, gasLimit, data); Player storage player = _players[address(playerAddress)]; uint256 energy = player.energy; uint256 txCharge = ((initialGas - gasleft()) + 10000) * tx.gasprice; uint256 freeEnergyFee = (txCharge * 10) / 100; // 10% extra is used for free energy uint256 poolFee = txCharge * 10; // 1000% is used for UBF require(energy >= freeEnergyFee + poolFee, "not enough energy"); energy -= (freeEnergyFee + poolFee); _pool.recordCharge{value: poolFee}(sender, txCharge, poolFee); if (msg.sender == sender) { // not metatx : use local private key so need to recharge local balance // TODO remove (once metatx is enabled) if (msg.sender.balance < MIN_BALANCE) { uint256 balanceToGive = MIN_BALANCE - msg.sender.balance; if (balanceToGive >= energy) { balanceToGive = energy; energy = 0; } else { energy -= balanceToGive; } if (balanceToGive > 0) { msg.sender.transfer(balanceToGive); } } } player.freeEnergy += uint128(freeEnergyFee); player.energy = uint128(energy); emit Call(success, returnData); } function isDelegateFor(address delegate, address playerAddress) external view returns (bool) { return _delegates[delegate] == playerAddress; } function refillAccount(address account) public payable { address payable sender = _msgSender(); _refill(sender, account, msg.value); } function refill() public payable { address payable sender = _msgSender(); _refill(sender, sender, msg.value); } function _refill( address payable sender, address account, uint256 value ) internal returns (uint256 refund) { uint128 energy = _players[account].energy; energy += uint128(value); if (energy > uint128(MAX_FOOD)) { energy = uint128(MAX_FOOD); refund = energy - MAX_FOOD; } _players[account].energy = energy; emit Refill(account, energy); if (refund > 0) { sender.transfer(refund); } } // TODO add Events for Delegates function addDelegate(address payable _delegate) public payable { address payable sender = _msgSender(); if (msg.value > 0) { _refill(sender, sender, msg.value); } _addDelegate(sender, _delegate); } function _addDelegate(address sender, address payable _delegate) internal { require(_delegate != address(0), "no zero address delegate"); require(_players[sender].energy >= uint128(MIN_BALANCE), "not enough energy"); _players[sender].energy -= uint128(MIN_BALANCE); _delegate.transfer(MIN_BALANCE); _delegates[_delegate] = sender; } function _getFirstParam(bytes memory data) internal pure returns (uint256) { if (data.length < 36) { return 0; } uint256 value; // solhint-disable-next-line security/no-inline-assembly assembly { value := mload(add(data, 36)) } return value; } function _executeWithSpecificGas( address to, uint256 gasLimit, bytes memory data ) internal returns (bool success, bytes memory returnData) { (success, returnData) = to.call.gas(gasLimit)(data); assert(gasleft() > gasLimit / 63); // not enough gas provided, assert to throw all gas // TODO use EIP-1930 } }
not enough gas provided, assert to throw all gas TODO use EIP-1930
function _executeWithSpecificGas( address to, uint256 gasLimit, bytes memory data ) internal returns (bool success, bytes memory returnData) { (success, returnData) = to.call.gas(gasLimit)(data); assert(gasleft() > gasLimit / 63); }
1,069,912
/** *Submitted for verification at Etherscan.io on 2021-08-02 */ // File: @sygnum/solidity-base-contracts/contracts/helpers/Initializable.sol pragma solidity 0.5.12; /** * @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, "Initializable: 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. uint256 cs; // solhint-disable-next-line assembly { cs := extcodesize(address) } return cs == 0; } function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @sygnum/solidity-base-contracts/contracts/role/interface/IBaseOperators.sol /** * @title IBaseOperators * @notice Interface for BaseOperators contract */ pragma solidity 0.5.12; interface IBaseOperators { function isOperator(address _account) external view returns (bool); function isAdmin(address _account) external view returns (bool); function isSystem(address _account) external view returns (bool); function isRelay(address _account) external view returns (bool); function isMultisig(address _contract) external view returns (bool); function confirmFor(address _address) external; function addOperator(address _account) external; function removeOperator(address _account) external; function addAdmin(address _account) external; function removeAdmin(address _account) external; function addSystem(address _account) external; function removeSystem(address _account) external; function addRelay(address _account) external; function removeRelay(address _account) external; function addOperatorAndAdmin(address _account) external; function removeOperatorAndAdmin(address _account) external; } // File: @sygnum/solidity-base-contracts/contracts/role/base/Operatorable.sol /** * @title Operatorable * @author Team 3301 <[email protected]> * @dev Operatorable contract stores the BaseOperators contract address, and modifiers for * contracts. */ pragma solidity 0.5.12; contract Operatorable is Initializable { IBaseOperators internal operatorsInst; address private operatorsPending; event OperatorsContractChanged(address indexed caller, address indexed operatorsAddress); event OperatorsContractPending(address indexed caller, address indexed operatorsAddress); /** * @dev Reverts if sender does not have operator role associated. */ modifier onlyOperator() { require(isOperator(msg.sender), "Operatorable: caller does not have the operator role"); _; } /** * @dev Reverts if sender does not have admin role associated. */ modifier onlyAdmin() { require(isAdmin(msg.sender), "Operatorable: caller does not have the admin role"); _; } /** * @dev Reverts if sender does not have system role associated. */ modifier onlySystem() { require(isSystem(msg.sender), "Operatorable: caller does not have the system role"); _; } /** * @dev Reverts if sender does not have multisig privileges. */ modifier onlyMultisig() { require(isMultisig(msg.sender), "Operatorable: caller does not have multisig role"); _; } /** * @dev Reverts if sender does not have admin or system role associated. */ modifier onlyAdminOrSystem() { require(isAdminOrSystem(msg.sender), "Operatorable: caller does not have the admin role nor system"); _; } /** * @dev Reverts if sender does not have operator or system role associated. */ modifier onlyOperatorOrSystem() { require(isOperatorOrSystem(msg.sender), "Operatorable: caller does not have the operator role nor system"); _; } /** * @dev Reverts if sender does not have the relay role associated. */ modifier onlyRelay() { require(isRelay(msg.sender), "Operatorable: caller does not have relay role associated"); _; } /** * @dev Reverts if sender does not have relay or operator role associated. */ modifier onlyOperatorOrRelay() { require( isOperator(msg.sender) || isRelay(msg.sender), "Operatorable: caller does not have the operator role nor relay" ); _; } /** * @dev Reverts if sender does not have relay or admin role associated. */ modifier onlyAdminOrRelay() { require( isAdmin(msg.sender) || isRelay(msg.sender), "Operatorable: caller does not have the admin role nor relay" ); _; } /** * @dev Reverts if sender does not have the operator, or system, or relay role associated. */ modifier onlyOperatorOrSystemOrRelay() { require( isOperator(msg.sender) || isSystem(msg.sender) || isRelay(msg.sender), "Operatorable: caller does not have the operator role nor system nor relay" ); _; } /** * @dev Initialization instead of constructor, called once. The setOperatorsContract function can be called only by Admin role with * confirmation through the operators contract. * @param _baseOperators BaseOperators contract address. */ function initialize(address _baseOperators) public initializer { _setOperatorsContract(_baseOperators); } /** * @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr) * where addr is the address of current contract instance. This is done to prevent the case when the new contract address is * broken and control of the contract can be lost in such case * @param _baseOperators BaseOperators contract address. */ function setOperatorsContract(address _baseOperators) public onlyAdmin { require(_baseOperators != address(0), "Operatorable: address of new operators contract can not be zero"); operatorsPending = _baseOperators; emit OperatorsContractPending(msg.sender, _baseOperators); } /** * @dev The function should be called from new operators contract by admin to ensure that operatorsPending address * is the real contract address. */ function confirmOperatorsContract() public { require(operatorsPending != address(0), "Operatorable: address of new operators contract can not be zero"); require(msg.sender == operatorsPending, "Operatorable: should be called from new operators contract"); _setOperatorsContract(operatorsPending); } /** * @return The address of the BaseOperators contract. */ function getOperatorsContract() public view returns (address) { return address(operatorsInst); } /** * @return The pending address of the BaseOperators contract. */ function getOperatorsPending() public view returns (address) { return operatorsPending; } /** * @return If '_account' has operator privileges. */ function isOperator(address _account) public view returns (bool) { return operatorsInst.isOperator(_account); } /** * @return If '_account' has admin privileges. */ function isAdmin(address _account) public view returns (bool) { return operatorsInst.isAdmin(_account); } /** * @return If '_account' has system privileges. */ function isSystem(address _account) public view returns (bool) { return operatorsInst.isSystem(_account); } /** * @return If '_account' has relay privileges. */ function isRelay(address _account) public view returns (bool) { return operatorsInst.isRelay(_account); } /** * @return If '_contract' has multisig privileges. */ function isMultisig(address _contract) public view returns (bool) { return operatorsInst.isMultisig(_contract); } /** * @return If '_account' has admin or system privileges. */ function isAdminOrSystem(address _account) public view returns (bool) { return (operatorsInst.isAdmin(_account) || operatorsInst.isSystem(_account)); } /** * @return If '_account' has operator or system privileges. */ function isOperatorOrSystem(address _account) public view returns (bool) { return (operatorsInst.isOperator(_account) || operatorsInst.isSystem(_account)); } /** INTERNAL FUNCTIONS */ function _setOperatorsContract(address _baseOperators) internal { require(_baseOperators != address(0), "Operatorable: address of new operators contract cannot be zero"); operatorsInst = IBaseOperators(_baseOperators); emit OperatorsContractChanged(msg.sender, _baseOperators); } } // File: zos-lib/contracts/upgradeability/Proxy.sol pragma solidity ^0.5.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // File: zos-lib/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library ZOSLibAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: zos-lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol pragma solidity ^0.5.0; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(ZOSLibAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol pragma solidity ^0.5.0; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } // File: zos-lib/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol pragma solidity ^0.5.0; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol pragma solidity ^0.5.0; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(_admin); } } // File: contracts/token/SygnumTokenProxy.sol /** * @title SygnumTokenProxy * @author Team 3301 <[email protected]> * @dev Proxies SygnumToken calls and enables SygnumToken upgradability. */ pragma solidity 0.5.12; contract SygnumTokenProxy is AdminUpgradeabilityProxy { /* solhint-disable no-empty-blocks */ constructor( address implementation, address proxyOwnerAddr, bytes memory data ) public AdminUpgradeabilityProxy(implementation, proxyOwnerAddr, data) {} /* solhint-enable no-empty-blocks */ } // File: contracts/factory/ProxyDeployer.sol /** * @title ProxyDeployer * @author Team 3301 <[email protected]> * @dev Library to deploy a proxy instance for a Sygnum. */ pragma solidity 0.5.12; library ProxyDeployer { /** * @dev Deploy the proxy instance and initialize it * @param _tokenImplementation Address of the logic contract * @param _proxyAdmin Address of the admin for the proxy * @param _data Bytecode needed for initialization * @return address New instance address */ function deployTokenProxy( address _tokenImplementation, address _proxyAdmin, bytes memory _data ) public returns (address) { SygnumTokenProxy proxy = new SygnumTokenProxy(_tokenImplementation, _proxyAdmin, _data); return address(proxy); } } // File: contracts/token/ERC20/ERC20Detailed.sol /** * @title ERC20Detailed * @author OpenZeppelin-Solidity = "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol", and rmeoval * of IERC20 due to " contract binary not set. Can't deploy new instance. * This contract may be abstract, not implement an abstract parent's methods completely * or not invoke an inherited contract's constructor correctly" */ pragma solidity 0.5.12; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed { string internal _name; string internal _symbol; uint8 internal _decimals; /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } // File: contracts/token/ERC20/ERC20SygnumDetailed.sol /** * @title ERC20SygnumDetailed * @author Team 3301 <[email protected]> * @dev ERC20 Standard Token with additional details and role set. */ pragma solidity 0.5.12; contract ERC20SygnumDetailed is ERC20Detailed, Operatorable { bytes4 private _category; string private _class; address private _issuer; event NameUpdated(address issuer, string name, address token); event SymbolUpdated(address issuer, string symbol, address token); event CategoryUpdated(address issuer, bytes4 category, address token); event ClassUpdated(address issuer, string class, address token); event IssuerUpdated(address issuer, address newIssuer, address token); /** * @dev Sets the values for `name`, `symbol`, `decimals`, `category`, `class` and `issuer`. All are * mutable apart from `issuer`, which is immutable. * @param name string * @param symbol string * @param decimals uint8 * @param category bytes4 * @param class string * @param issuer address */ function _setDetails( string memory name, string memory symbol, uint8 decimals, bytes4 category, string memory class, address issuer ) internal { _name = name; _symbol = symbol; _decimals = decimals; _category = category; _class = class; _issuer = issuer; } /** * @dev Returns the category of the token. */ function category() public view returns (bytes4) { return _category; } /** * @dev Returns the class of the token. */ function class() public view returns (string memory) { return _class; } /** * @dev Returns the issuer of the token. */ function issuer() public view returns (address) { return _issuer; } /** * @dev Updates the name of the token, only callable by Sygnum operator. * @param name_ The new name. */ function updateName(string memory name_) public onlyOperator { _name = name_; emit NameUpdated(msg.sender, _name, address(this)); } /** * @dev Updates the symbol of the token, only callable by Sygnum operator. * @param symbol_ The new symbol. */ function updateSymbol(string memory symbol_) public onlyOperator { _symbol = symbol_; emit SymbolUpdated(msg.sender, symbol_, address(this)); } /** * @dev Updates the category of the token, only callable by Sygnum operator. * @param category_ The new cateogry. */ function updateCategory(bytes4 category_) public onlyOperator { _category = category_; emit CategoryUpdated(msg.sender, _category, address(this)); } /** * @dev Updates the class of the token, only callable by Sygnum operator. * @param class_ The new class. */ function updateClass(string memory class_) public onlyOperator { _class = class_; emit ClassUpdated(msg.sender, _class, address(this)); } /** * @dev Updates issuer ownership, only callable by Sygnum operator. * @param issuer_ The new issuer. */ function updateIssuer(address issuer_) public onlyOperator { _issuer = issuer_; emit IssuerUpdated(msg.sender, _issuer, address(this)); } } // File: openzeppelin-solidity/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Overload/ERC20.sol pragma solidity 0.5.12; /** * @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 {ERC20Mintable}. * * 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) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 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 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 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _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 { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance") ); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/interface/IWhitelist.sol pragma solidity 0.5.12; /** * @title IWhitelist * @notice Interface for Whitelist contract */ contract IWhitelist { function isWhitelisted(address _account) external view returns (bool); function toggleWhitelist(address _account, bool _toggled) external; } // File: @sygnum/solidity-base-contracts/contracts/helpers/instance/Whitelistable.sol /** * @title Whitelistable * @author Team 3301 <[email protected]> * @dev Whitelistable contract stores the Whitelist contract address, and modifiers for * contracts. */ pragma solidity 0.5.12; contract Whitelistable is Initializable, Operatorable { IWhitelist internal whitelistInst; address private whitelistPending; event WhitelistContractChanged(address indexed caller, address indexed whitelistAddress); event WhitelistContractPending(address indexed caller, address indexed whitelistAddress); /** * @dev Reverts if _account is not whitelisted. * @param _account address to determine if whitelisted. */ modifier whenWhitelisted(address _account) { require(isWhitelisted(_account), "Whitelistable: account is not whitelisted"); _; } /** * @dev Initialization instead of constructor, called once. The setWhitelistContract function can be called only by Admin role with * confirmation through the whitelist contract. * @param _whitelist Whitelist contract address. * @param _baseOperators BaseOperators contract address. */ function initialize(address _baseOperators, address _whitelist) public initializer { _setOperatorsContract(_baseOperators); _setWhitelistContract(_whitelist); } /** * @dev Set the new the address of Whitelist contract, should be confirmed from whitelist contract by calling confirmFor(addr) * where addr is the address of current contract instance. This is done to prevent the case when the new contract address is * broken and control of the contract can be lost in such case * @param _whitelist Whitelist contract address. */ function setWhitelistContract(address _whitelist) public onlyAdmin { require(_whitelist != address(0), "Whitelistable: address of new whitelist contract can not be zero"); whitelistPending = _whitelist; emit WhitelistContractPending(msg.sender, _whitelist); } /** * @dev The function should be called from new whitelist contract by admin to insure that whitelistPending address * is the real contract address. */ function confirmWhitelistContract() public { require(whitelistPending != address(0), "Whitelistable: address of new whitelist contract can not be zero"); require(msg.sender == whitelistPending, "Whitelistable: should be called from new whitelist contract"); _setWhitelistContract(whitelistPending); } /** * @return The address of the Whitelist contract. */ function getWhitelistContract() public view returns (address) { return address(whitelistInst); } /** * @return The pending address of the Whitelist contract. */ function getWhitelistPending() public view returns (address) { return whitelistPending; } /** * @return If '_account' is whitelisted. */ function isWhitelisted(address _account) public view returns (bool) { return whitelistInst.isWhitelisted(_account); } /** INTERNAL FUNCTIONS */ function _setWhitelistContract(address _whitelist) internal { require(_whitelist != address(0), "Whitelistable: address of new whitelist contract cannot be zero"); whitelistInst = IWhitelist(_whitelist); emit WhitelistContractChanged(msg.sender, _whitelist); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Whitelist.sol /** * @title ERC20Whitelist * @author Team 3301 <[email protected]> * @dev Overloading ERC20 functions to ensure that addresses attempting to particular * actions are whitelisted. */ pragma solidity 0.5.12; contract ERC20Whitelist is ERC20, Whitelistable { /** * @dev Overload transfer function to validate sender and receiver are whitelisted. * @param to address that recieves the funds. * @param value amount of funds. */ function transfer(address to, uint256 value) public whenWhitelisted(msg.sender) whenWhitelisted(to) returns (bool) { return super.transfer(to, value); } /** * @dev Overload approve function to validate sender and spender are whitelisted. * @param spender address that can spend the funds. * @param value amount of funds. */ function approve(address spender, uint256 value) public whenWhitelisted(msg.sender) whenWhitelisted(spender) returns (bool) { return super.approve(spender, value); } /** * @dev Overload transferFrom function to validate sender, from and receiver are whitelisted. * @param from address that funds will be transferred from. * @param to address that funds will be transferred to. * @param value amount of funds. */ function transferFrom( address from, address to, uint256 value ) public whenWhitelisted(msg.sender) whenWhitelisted(from) whenWhitelisted(to) returns (bool) { return super.transferFrom(from, to, value); } /** * @dev Overload increaseAllowance validate sender and spender are whitelisted. * @param spender address that will be allowed to transfer funds. * @param addedValue amount of funds to added to current allowance. */ function increaseAllowance(address spender, uint256 addedValue) public whenWhitelisted(spender) whenWhitelisted(msg.sender) returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Overload decreaseAllowance validate sender and spender are whitelisted. * @param spender address that will be allowed to transfer funds. * @param subtractedValue amount of funds to be deducted to current allowance. */ function decreaseAllowance(address spender, uint256 subtractedValue) public whenWhitelisted(spender) whenWhitelisted(msg.sender) returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Overload _burn function to ensure that account has been whitelisted. * @param account address that funds will be burned from. * @param value amount of funds that will be burned. */ function _burn(address account, uint256 value) internal whenWhitelisted(account) { super._burn(account, value); } /** * @dev Overload _burnFrom function to ensure sender and account have been whitelisted. * @param account address that funds will be burned from allowance. * @param amount amount of funds that will be burned. */ function _burnFrom(address account, uint256 amount) internal whenWhitelisted(msg.sender) whenWhitelisted(account) { super._burnFrom(account, amount); } /** * @dev Overload _mint function to ensure account has been whitelisted. * @param account address that funds will be minted to. * @param amount amount of funds that will be minted. */ function _mint(address account, uint256 amount) internal whenWhitelisted(account) { super._mint(account, amount); } } // File: @sygnum/solidity-base-contracts/contracts/role/interface/ITraderOperators.sol /** * @title ITraderOperators * @notice Interface for TraderOperators contract */ pragma solidity 0.5.12; contract ITraderOperators { function isTrader(address _account) external view returns (bool); function addTrader(address _account) external; function removeTrader(address _account) external; } // File: @sygnum/solidity-base-contracts/contracts/role/trader/TraderOperatorable.sol /** * @title TraderOperatorable * @author Team 3301 <[email protected]> * @dev TraderOperatorable contract stores TraderOperators contract address, and modifiers for * contracts. */ pragma solidity 0.5.12; contract TraderOperatorable is Operatorable { ITraderOperators internal traderOperatorsInst; address private traderOperatorsPending; event TraderOperatorsContractChanged(address indexed caller, address indexed traderOperatorsAddress); event TraderOperatorsContractPending(address indexed caller, address indexed traderOperatorsAddress); /** * @dev Reverts if sender does not have the trader role associated. */ modifier onlyTrader() { require(isTrader(msg.sender), "TraderOperatorable: caller is not trader"); _; } /** * @dev Reverts if sender does not have the operator or trader role associated. */ modifier onlyOperatorOrTraderOrSystem() { require( isOperator(msg.sender) || isTrader(msg.sender) || isSystem(msg.sender), "TraderOperatorable: caller is not trader or operator or system" ); _; } /** * @dev Initialization instead of constructor, called once. The setTradersOperatorsContract function can be called only by Admin role with * confirmation through the operators contract. * @param _baseOperators BaseOperators contract address. * @param _traderOperators TraderOperators contract address. */ function initialize(address _baseOperators, address _traderOperators) public initializer { super.initialize(_baseOperators); _setTraderOperatorsContract(_traderOperators); } /** * @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr) * where addr is the address of current contract instance. This is done to prevent the case when the new contract address is * broken and control of the contract can be lost in such case * @param _traderOperators TradeOperators contract address. */ function setTraderOperatorsContract(address _traderOperators) public onlyAdmin { require( _traderOperators != address(0), "TraderOperatorable: address of new traderOperators contract can not be zero" ); traderOperatorsPending = _traderOperators; emit TraderOperatorsContractPending(msg.sender, _traderOperators); } /** * @dev The function should be called from new operators contract by admin to insure that traderOperatorsPending address * is the real contract address. */ function confirmTraderOperatorsContract() public { require( traderOperatorsPending != address(0), "TraderOperatorable: address of pending traderOperators contract can not be zero" ); require( msg.sender == traderOperatorsPending, "TraderOperatorable: should be called from new traderOperators contract" ); _setTraderOperatorsContract(traderOperatorsPending); } /** * @return The address of the TraderOperators contract. */ function getTraderOperatorsContract() public view returns (address) { return address(traderOperatorsInst); } /** * @return The pending TraderOperators contract address */ function getTraderOperatorsPending() public view returns (address) { return traderOperatorsPending; } /** * @return If '_account' has trader privileges. */ function isTrader(address _account) public view returns (bool) { return traderOperatorsInst.isTrader(_account); } /** INTERNAL FUNCTIONS */ function _setTraderOperatorsContract(address _traderOperators) internal { require( _traderOperators != address(0), "TraderOperatorable: address of new traderOperators contract can not be zero" ); traderOperatorsInst = ITraderOperators(_traderOperators); emit TraderOperatorsContractChanged(msg.sender, _traderOperators); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/Pausable.sol /** * @title Pausable * @author Team 3301 <[email protected]> * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account in the TraderOperatorable * contract. */ pragma solidity 0.5.12; contract Pausable is TraderOperatorable { event Paused(address indexed account); event Unpaused(address indexed account); bool internal _paused; constructor() internal { _paused = false; } /** * @dev Reverts if contract is paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Reverts if contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by operator to pause child contract. The contract * must not already be paused. */ function pause() public onlyOperatorOrTraderOrSystem whenNotPaused { _paused = true; emit Paused(msg.sender); } /** @dev Called by operator to pause child contract. The contract * must already be paused. */ function unpause() public onlyOperatorOrTraderOrSystem whenPaused { _paused = false; emit Unpaused(msg.sender); } /** * @return If child contract is already paused or not. */ function isPaused() public view returns (bool) { return _paused; } /** * @return If child contract is not paused. */ function isNotPaused() public view returns (bool) { return !_paused; } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Pausable.sol /** * @title ERC20Pausable * @author Team 3301 <[email protected]> * @dev Overloading ERC20 functions to ensure that the contract has not been paused. */ pragma solidity 0.5.12; contract ERC20Pausable is ERC20, Pausable { /** * @dev Overload transfer function to ensure contract has not been paused. * @param to address that recieves the funds. * @param value amount of funds. */ function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } /** * @dev Overload approve function to ensure contract has not been paused. * @param spender address that can spend the funds. * @param value amount of funds. */ function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } /** * @dev Overload transferFrom function to ensure contract has not been paused. * @param from address that funds will be transferred from. * @param to address that funds will be transferred to. * @param value amount of funds. */ function transferFrom( address from, address to, uint256 value ) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } /** * @dev Overload increaseAllowance function to ensure contract has not been paused. * @param spender address that will be allowed to transfer funds. * @param addedValue amount of funds to added to current allowance. */ function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Overload decreaseAllowance function to ensure contract has not been paused. * @param spender address that will be allowed to transfer funds. * @param subtractedValue amount of funds to be deducted to current allowance. */ function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Overload _burn function to ensure contract has not been paused. * @param account address that funds will be burned from. * @param value amount of funds that will be burned. */ function _burn(address account, uint256 value) internal whenNotPaused { super._burn(account, value); } /** * @dev Overload _burnFrom function to ensure contract has not been paused. * @param account address that funds will be burned from allowance. * @param amount amount of funds that will be burned. */ function _burnFrom(address account, uint256 amount) internal whenNotPaused { super._burnFrom(account, amount); } /** * @dev Overload _mint function to ensure contract has not been paused. * @param account address that funds will be minted to. * @param amount amount of funds that will be minted. */ function _mint(address account, uint256 amount) internal whenNotPaused { super._mint(account, amount); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Mintable.sol /** * @title ERC20Mintable * @author Team 3301 <[email protected]> * @dev For blocking and unblocking particular user funds. */ pragma solidity 0.5.12; contract ERC20Mintable is ERC20, Operatorable { /** * @dev Overload _mint to ensure only operator or system can mint funds. * @param account address that will recieve new funds. * @param amount of funds to be minted. */ function _mint(address account, uint256 amount) internal onlyOperatorOrSystem { require(amount > 0, "ERC20Mintable: amount has to be greater than 0"); super._mint(account, amount); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Snapshot.sol /** * @title ERC20Snapshot * @author Team 3301 <[email protected]> * @notice Records historical balances. */ pragma solidity 0.5.12; contract ERC20Snapshot is ERC20 { using SafeMath for uint256; /** * @dev `Snapshot` is the structure that attaches a block number to a * given value. The block number attached is the one that last changed the value */ struct Snapshot { uint256 fromBlock; // `fromBlock` is the block number at which the value was generated from uint256 value; // `value` is the amount of tokens at a specific block number } /** * @dev `_snapshotBalances` is the map that tracks the balance of each address, in this * contract when the balance changes the block number that the change * occurred is also included in the map */ mapping(address => Snapshot[]) private _snapshotBalances; // Tracks the history of the `totalSupply` of the token Snapshot[] private _snapshotTotalSupply; /** * @dev Queries the balance of `_owner` at a specific `_blockNumber` * @param _owner The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at `_blockNumber` */ function balanceOfAt(address _owner, uint256 _blockNumber) public view returns (uint256) { return getValueAt(_snapshotBalances[_owner], _blockNumber); } /** * @dev Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` */ function totalSupplyAt(uint256 _blockNumber) public view returns (uint256) { return getValueAt(_snapshotTotalSupply, _blockNumber); } /** * @dev `getValueAt` retrieves the number of tokens at a given block number * @param checkpoints The history of values being queried * @param _block The block number to retrieve the value at * @return The number of tokens being queried */ function getValueAt(Snapshot[] storage checkpoints, uint256 _block) internal view returns (uint256) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) { return checkpoints[checkpoints.length.sub(1)].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min; uint256 max = checkpoints.length.sub(1); while (max > min) { uint256 mid = (max.add(min).add(1)).div(2); if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid.sub(1); } } return checkpoints[min].value; } /** * @dev `updateValueAtNow` used to update the `_snapshotBalances` map and the `_snapshotTotalSupply` * @param checkpoints The history of data being updated * @param _value The new number of tokens */ function updateValueAtNow(Snapshot[] storage checkpoints, uint256 _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) { checkpoints.push(Snapshot(block.number, _value)); } else { checkpoints[checkpoints.length.sub(1)].value = _value; } } /** * @dev Internal function that transfers an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param to The account that will receive the created tokens. * @param value The amount that will be created. */ function transfer(address to, uint256 value) public returns (bool result) { result = super.transfer(to, value); updateValueAtNow(_snapshotTotalSupply, totalSupply()); updateValueAtNow(_snapshotBalances[msg.sender], balanceOf(msg.sender)); updateValueAtNow(_snapshotBalances[to], balanceOf(to)); } /** * @dev Internal function that transfers an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param from The account that funds will be taken from. * @param to The account that funds will be given too. * @param value The amount of funds to be transferred.. */ function transferFrom( address from, address to, uint256 value ) public returns (bool result) { result = super.transferFrom(from, to, value); updateValueAtNow(_snapshotTotalSupply, totalSupply()); updateValueAtNow(_snapshotBalances[from], balanceOf(from)); updateValueAtNow(_snapshotBalances[to], balanceOf(to)); } /** * @dev Internal function that confiscates an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param confiscatee The account that funds will be taken from. * @param receiver The account that funds will be given too. * @param amount The amount of funds to be transferred.. */ function _confiscate( address confiscatee, address receiver, uint256 amount ) internal { super._transfer(confiscatee, receiver, amount); updateValueAtNow(_snapshotTotalSupply, totalSupply()); updateValueAtNow(_snapshotBalances[confiscatee], balanceOf(confiscatee)); updateValueAtNow(_snapshotBalances[receiver], balanceOf(receiver)); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { super._mint(account, amount); updateValueAtNow(_snapshotTotalSupply, totalSupply()); updateValueAtNow(_snapshotBalances[account], balanceOf(account)); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { super._burn(account, amount); updateValueAtNow(_snapshotTotalSupply, totalSupply()); updateValueAtNow(_snapshotBalances[account], balanceOf(account)); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burnFor(address account, uint256 amount) internal { super._burn(account, amount); updateValueAtNow(_snapshotTotalSupply, totalSupply()); updateValueAtNow(_snapshotBalances[account], balanceOf(account)); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burnFrom(address account, uint256 amount) internal { super._burnFrom(account, amount); updateValueAtNow(_snapshotTotalSupply, totalSupply()); updateValueAtNow(_snapshotBalances[account], balanceOf(account)); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Burnable.sol /** * @title ERC20Burnable * @author Team 3301 <[email protected]> * @dev For burning funds from particular user addresses. */ pragma solidity 0.5.12; contract ERC20Burnable is ERC20Snapshot, Operatorable { /** * @dev Overload ERC20 _burnFor, burning funds from a particular users address. * @param account address to burn funds from. * @param amount of funds to burn. */ function _burnFor(address account, uint256 amount) internal onlyOperator { super._burn(account, amount); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/Freezable.sol /** * @title Freezable * @author Team 3301 <[email protected]> * @dev Freezable contract to freeze functionality for particular addresses. Freezing/unfreezing is controlled * by operators in Operatorable contract which is initialized with the relevant BaseOperators address. */ pragma solidity 0.5.12; contract Freezable is Operatorable { mapping(address => bool) public frozen; event FreezeToggled(address indexed account, bool frozen); /** * @dev Reverts if address is empty. * @param _address address to validate. */ modifier onlyValidAddress(address _address) { require(_address != address(0), "Freezable: Empty address"); _; } /** * @dev Reverts if account address is frozen. * @param _account address to validate is not frozen. */ modifier whenNotFrozen(address _account) { require(!frozen[_account], "Freezable: account is frozen"); _; } /** * @dev Reverts if account address is not frozen. * @param _account address to validate is frozen. */ modifier whenFrozen(address _account) { require(frozen[_account], "Freezable: account is not frozen"); _; } /** * @dev Getter to determine if address is frozen. * @param _account address to determine if frozen or not. * @return bool is frozen */ function isFrozen(address _account) public view returns (bool) { return frozen[_account]; } /** * @dev Toggle freeze/unfreeze on _account address, with _toggled being true/false. * @param _account address to toggle. * @param _toggled freeze/unfreeze. */ function toggleFreeze(address _account, bool _toggled) public onlyValidAddress(_account) onlyOperator { frozen[_account] = _toggled; emit FreezeToggled(_account, _toggled); } /** * @dev Batch freeze/unfreeze multiple addresses, with _toggled being true/false. * @param _addresses address array. * @param _toggled freeze/unfreeze. */ function batchToggleFreeze(address[] memory _addresses, bool _toggled) public { require(_addresses.length <= 256, "Freezable: batch count is greater than 256"); for (uint256 i = 0; i < _addresses.length; i++) { toggleFreeze(_addresses[i], _toggled); } } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Freezable.sol /** * @title ERC20Freezable * @author Team 3301 <[email protected]> * @dev Overloading ERC20 functions to ensure client addresses are not frozen for particular actions. */ pragma solidity 0.5.12; contract ERC20Freezable is ERC20, Freezable { /** * @dev Overload transfer function to ensure sender and receiver have not been frozen. * @param to address that recieves the funds. * @param value amount of funds. */ function transfer(address to, uint256 value) public whenNotFrozen(msg.sender) whenNotFrozen(to) returns (bool) { return super.transfer(to, value); } /** * @dev Overload approve function to ensure sender and receiver have not been frozen. * @param spender address that can spend the funds. * @param value amount of funds. */ function approve(address spender, uint256 value) public whenNotFrozen(msg.sender) whenNotFrozen(spender) returns (bool) { return super.approve(spender, value); } /** * @dev Overload transferFrom function to ensure sender, approver and receiver have not been frozen. * @param from address that funds will be transferred from. * @param to address that funds will be transferred to. * @param value amount of funds. */ function transferFrom( address from, address to, uint256 value ) public whenNotFrozen(msg.sender) whenNotFrozen(from) whenNotFrozen(to) returns (bool) { return super.transferFrom(from, to, value); } /** * @dev Overload increaseAllowance function to ensure sender and spender have not been frozen. * @param spender address that will be allowed to transfer funds. * @param addedValue amount of funds to added to current allowance. */ function increaseAllowance(address spender, uint256 addedValue) public whenNotFrozen(msg.sender) whenNotFrozen(spender) returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Overload decreaseAllowance function to ensure sender and spender have not been frozen. * @param spender address that will be allowed to transfer funds. * @param subtractedValue amount of funds to be deducted to current allowance. */ function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotFrozen(msg.sender) whenNotFrozen(spender) returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Overload _burnfrom function to ensure sender and user to be burned from have not been frozen. * @param account account that funds will be burned from. * @param amount amount of funds to be burned. */ function _burnFrom(address account, uint256 amount) internal whenNotFrozen(msg.sender) whenNotFrozen(account) { super._burnFrom(account, amount); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Destroyable.sol /** * @title ERC20Destroyable * @author Team 3301 <[email protected]> * @notice Allows operator to destroy contract. */ pragma solidity 0.5.12; contract ERC20Destroyable is Operatorable { event Destroyed(address indexed caller, address indexed account, address indexed contractAddress); function destroy(address payable to) public onlyOperator { emit Destroyed(msg.sender, to, address(this)); selfdestruct(to); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Tradeable.sol /** * @title ERC20Tradeable * @author Team 3301 <[email protected]> * @dev Trader accounts can approve particular addresses on behalf of a user. */ pragma solidity 0.5.12; contract ERC20Tradeable is ERC20, TraderOperatorable { /** * @dev Trader can approve users balance to a particular address for a particular amount. * @param _owner address that approves the funds. * @param _spender address that spends the funds. * @param _value amount of funds. */ function approveOnBehalf( address _owner, address _spender, uint256 _value ) public onlyTrader { super._approve(_owner, _spender, _value); } } // File: @sygnum/solidity-base-contracts/contracts/role/interface/IBlockerOperators.sol /** * @title IBlockerOperators * @notice Interface for BlockerOperators contract */ pragma solidity 0.5.12; contract IBlockerOperators { function isBlocker(address _account) external view returns (bool); function addBlocker(address _account) external; function removeBlocker(address _account) external; } // File: @sygnum/solidity-base-contracts/contracts/role/blocker/BlockerOperatorable.sol /** * @title BlockerOperatorable * @author Team 3301 <[email protected]> * @dev BlockerOperatorable contract stores BlockerOperators contract address, and modifiers for * contracts. */ pragma solidity 0.5.12; contract BlockerOperatorable is Operatorable { IBlockerOperators internal blockerOperatorsInst; address private blockerOperatorsPending; event BlockerOperatorsContractChanged(address indexed caller, address indexed blockerOperatorAddress); event BlockerOperatorsContractPending(address indexed caller, address indexed blockerOperatorAddress); /** * @dev Reverts if sender does not have the blocker role associated. */ modifier onlyBlocker() { require(isBlocker(msg.sender), "BlockerOperatorable: caller is not blocker role"); _; } /** * @dev Reverts if sender does not have the blocker or operator role associated. */ modifier onlyBlockerOrOperator() { require( isBlocker(msg.sender) || isOperator(msg.sender), "BlockerOperatorable: caller is not blocker or operator role" ); _; } /** * @dev Initialization instead of constructor, called once. The setBlockerOperatorsContract function can be called only by Admin role with * confirmation through the operators contract. * @param _baseOperators BaseOperators contract address. * @param _blockerOperators BlockerOperators contract address. */ function initialize(address _baseOperators, address _blockerOperators) public initializer { super.initialize(_baseOperators); _setBlockerOperatorsContract(_blockerOperators); } /** * @dev Set the new the address of BlockerOperators contract, should be confirmed from BlockerOperators contract by calling confirmFor(addr) * where addr is the address of current contract instance. This is done to prevent the case when the new contract address is * broken and control of the contract can be lost in such case. * @param _blockerOperators BlockerOperators contract address. */ function setBlockerOperatorsContract(address _blockerOperators) public onlyAdmin { require( _blockerOperators != address(0), "BlockerOperatorable: address of new blockerOperators contract can not be zero." ); blockerOperatorsPending = _blockerOperators; emit BlockerOperatorsContractPending(msg.sender, _blockerOperators); } /** * @dev The function should be called from new BlockerOperators contract by admin to insure that blockerOperatorsPending address * is the real contract address. */ function confirmBlockerOperatorsContract() public { require( blockerOperatorsPending != address(0), "BlockerOperatorable: address of pending blockerOperators contract can not be zero" ); require( msg.sender == blockerOperatorsPending, "BlockerOperatorable: should be called from new blockerOperators contract" ); _setBlockerOperatorsContract(blockerOperatorsPending); } /** * @return The address of the BlockerOperators contract. */ function getBlockerOperatorsContract() public view returns (address) { return address(blockerOperatorsInst); } /** * @return The pending BlockerOperators contract address */ function getBlockerOperatorsPending() public view returns (address) { return blockerOperatorsPending; } /** * @return If '_account' has blocker privileges. */ function isBlocker(address _account) public view returns (bool) { return blockerOperatorsInst.isBlocker(_account); } /** INTERNAL FUNCTIONS */ function _setBlockerOperatorsContract(address _blockerOperators) internal { require( _blockerOperators != address(0), "BlockerOperatorable: address of new blockerOperators contract can not be zero" ); blockerOperatorsInst = IBlockerOperators(_blockerOperators); emit BlockerOperatorsContractChanged(msg.sender, _blockerOperators); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Blockable.sol /** * @title ERC20Blockable * @author Team 3301 <[email protected]> * @dev For blocking and unblocking particular user funds. */ pragma solidity 0.5.12; contract ERC20Blockable is ERC20, BlockerOperatorable { uint256 public totalBlockedBalance; mapping(address => uint256) public _blockedBalances; event Blocked(address indexed blocker, address indexed account, uint256 value); event UnBlocked(address indexed blocker, address indexed account, uint256 value); /** * @dev Block funds, and move funds from _balances into _blockedBalances. * @param _account address to block funds. * @param _amount of funds to block. */ function block(address _account, uint256 _amount) public onlyBlockerOrOperator { _balances[_account] = _balances[_account].sub(_amount); _blockedBalances[_account] = _blockedBalances[_account].add(_amount); totalBlockedBalance = totalBlockedBalance.add(_amount); emit Blocked(msg.sender, _account, _amount); } /** * @dev Unblock funds, and move funds from _blockedBalances into _balances. * @param _account address to unblock funds. * @param _amount of funds to unblock. */ function unblock(address _account, uint256 _amount) public onlyBlockerOrOperator { _balances[_account] = _balances[_account].add(_amount); _blockedBalances[_account] = _blockedBalances[_account].sub(_amount); totalBlockedBalance = totalBlockedBalance.sub(_amount); emit UnBlocked(msg.sender, _account, _amount); } /** * @dev Getter for the amount of blocked balance for a particular address. * @param _account address to get blocked balance. * @return amount of blocked balance. */ function blockedBalanceOf(address _account) public view returns (uint256) { return _blockedBalances[_account]; } /** * @dev Getter for the total amount of blocked funds for all users. * @return amount of total blocked balance. */ function getTotalBlockedBalance() public view returns (uint256) { return totalBlockedBalance; } } // File: contracts/token/SygnumToken.sol /** * @title SygnumToken * @author Team 3301 <[email protected]> * @notice ERC20 token with additional features. */ pragma solidity 0.5.12; contract SygnumToken is ERC20Snapshot, ERC20SygnumDetailed, ERC20Pausable, ERC20Mintable, ERC20Whitelist, ERC20Tradeable, ERC20Blockable, ERC20Burnable, ERC20Freezable, ERC20Destroyable { event Minted(address indexed minter, address indexed account, uint256 value); event Burned(address indexed burner, uint256 value); event BurnedFor(address indexed burner, address indexed account, uint256 value); event Confiscated(address indexed account, uint256 amount, address indexed receiver); uint16 internal constant BATCH_LIMIT = 256; /** * @dev Initialize contracts. * @param _baseOperators Base operators contract address. * @param _whitelist Whitelist contract address. * @param _traderOperators Trader operators contract address. * @param _blockerOperators Blocker operators contract address. */ function initializeContractsAndConstructor( string memory _name, string memory _symbol, uint8 _decimals, bytes4 _category, string memory _class, address _issuer, address _baseOperators, address _whitelist, address _traderOperators, address _blockerOperators ) public initializer { super.initialize(_baseOperators); _setWhitelistContract(_whitelist); _setTraderOperatorsContract(_traderOperators); _setBlockerOperatorsContract(_blockerOperators); _setDetails(_name, _symbol, _decimals, _category, _class, _issuer); } /** * @dev Burn. * @param _amount Amount of tokens to burn. */ function burn(uint256 _amount) public { require(!isFrozen(msg.sender), "SygnumToken: Account must not be frozen."); super._burn(msg.sender, _amount); emit Burned(msg.sender, _amount); } /** * @dev BurnFor. * @param _account Address to burn tokens for. * @param _amount Amount of tokens to burn. */ function burnFor(address _account, uint256 _amount) public { super._burnFor(_account, _amount); emit BurnedFor(msg.sender, _account, _amount); } /** * @dev BurnFrom. * @param _account Address to burn tokens from. * @param _amount Amount of tokens to burn. */ function burnFrom(address _account, uint256 _amount) public { super._burnFrom(_account, _amount); emit Burned(_account, _amount); } /** * @dev Mint. * @param _account Address to mint tokens to. * @param _amount Amount to mint. */ function mint(address _account, uint256 _amount) public { if (isSystem(msg.sender)) { require(!isFrozen(_account), "SygnumToken: Account must not be frozen if system calling."); } super._mint(_account, _amount); emit Minted(msg.sender, _account, _amount); } /** * @dev Confiscate. * @param _confiscatee Account to confiscate funds from. * @param _receiver Account to transfer confiscated funds to. * @param _amount Amount of tokens to confiscate. */ function confiscate( address _confiscatee, address _receiver, uint256 _amount ) public onlyOperator whenNotPaused whenWhitelisted(_receiver) whenWhitelisted(_confiscatee) { super._confiscate(_confiscatee, _receiver, _amount); emit Confiscated(_confiscatee, _amount, _receiver); } /** * @dev Batch burn for. * @param _amounts Array of all values to burn. * @param _accounts Array of all addresses to burn from. */ function batchBurnFor(address[] memory _accounts, uint256[] memory _amounts) public { require(_accounts.length == _amounts.length, "SygnumToken: values and recipients are not equal."); require(_accounts.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT."); for (uint256 i = 0; i < _accounts.length; i++) { burnFor(_accounts[i], _amounts[i]); } } /** * @dev Batch mint. * @param _accounts Array of all addresses to mint to. * @param _amounts Array of all values to mint. */ function batchMint(address[] memory _accounts, uint256[] memory _amounts) public { require(_accounts.length == _amounts.length, "SygnumToken: values and recipients are not equal."); require(_accounts.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT."); for (uint256 i = 0; i < _accounts.length; i++) { mint(_accounts[i], _amounts[i]); } } /** * @dev Batch confiscate to a maximum of 256 addresses. * @param _confiscatees array of addresses whose funds are being confiscated * @param _receivers array of addresses who's receiving the funds * @param _values array of values of funds being confiscated */ function batchConfiscate( address[] memory _confiscatees, address[] memory _receivers, uint256[] memory _values ) public returns (bool) { require( _confiscatees.length == _values.length && _receivers.length == _values.length, "SygnumToken: confiscatees, recipients and values are not equal." ); require(_confiscatees.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT."); for (uint256 i = 0; i < _confiscatees.length; i++) { confiscate(_confiscatees[i], _receivers[i], _values[i]); } } } // File: contracts/token/upgrade/prd/SygnumTokenV1.sol /** * @title MetadataUpgrade * @author Team 3301 <[email protected]> * @dev Upgraded SygnumToken. This upgrade adds the "tokenURI" field, which can hold a link to off chain token metadata. */ pragma solidity 0.5.12; contract SygnumTokenV1 is SygnumToken { string public tokenURI; bool public initializedV1; event TokenUriUpdated(string newToken); // changed back to public for tests function initializeContractsAndConstructor( string memory _name, string memory _symbol, uint8 _decimals, bytes4 _category, string memory _class, address _issuer, address _baseOperators, address _whitelist, address _traderOperators, address _blockerOperators, string memory _tokenURI ) public { require(!initializedV1, "SygnumTokenV1: already initialized"); super.initializeContractsAndConstructor( _name, _symbol, _decimals, _category, _class, _issuer, _baseOperators, _whitelist, _traderOperators, _blockerOperators ); initializeV1(_tokenURI); } function initializeV1(string memory _tokenURI) public { require(!initializedV1, "SygnumTokenV1: already initialized"); tokenURI = _tokenURI; initializedV1 = true; } function updateTokenURI(string memory _newToken) public onlyOperator { tokenURI = _newToken; emit TokenUriUpdated(_newToken); } } // File: contracts/factory/Details.sol /** * @title Details * @author Team 3301 <[email protected]> * @notice Shared library for Sygnum token details struct. */ pragma solidity 0.5.12; library Details { struct TokenDetails { string name; string symbol; uint8 decimals; bytes4 category; string class; address issuer; string tokenURI; } } // File: contracts/factory/TokenDeployer.sol /** * @title TokenDeployer * @author Team 3301 <[email protected]> * @dev Library to deploy and initialize a new instance of Sygnum Equity Token. * This is commonly used by a TokenFactory to automatically deploy and configure */ pragma experimental ABIEncoderV2; pragma solidity 0.5.12; library TokenDeployer { /** * @dev Initialize a token contracts. * @param _proxy Address of the proxy * @param _baseOperators Address of the base operator role contract * @param _whitelist Address of the whitelist contract * @param _traderOperators Address of the trader operator role contract * @param _blockerOperators Address of the blocker operator role contract * @param _details token details as defined by the TokenDetails struct */ function initializeToken( address _proxy, address _baseOperators, address _whitelist, address _traderOperators, address _blockerOperators, Details.TokenDetails memory _details ) public { SygnumTokenV1(_proxy).initializeContractsAndConstructor( _details.name, _details.symbol, _details.decimals, _details.category, _details.class, _details.issuer, _baseOperators, _whitelist, _traderOperators, _blockerOperators, _details.tokenURI ); } } // File: contracts/factory/TokenFactory.sol /** * @title TokenFactory * @author Team 3301 <[email protected]> * @dev Token factory to be used by operators to deploy arbitrary Sygnum Equity Token. */ pragma solidity 0.5.12; contract TokenFactory is Initializable, Operatorable { address public whitelist; address public proxyAdmin; address public implementation; address public traderOperators; address public blockerOperators; event UpdatedWhitelist(address indexed whitelist); event UpdatedTraderOperators(address indexed traderOperators); event UpdatedBlockerOperators(address indexed blockerOperators); event UpdatedProxyAdmin(address indexed proxyAdmin); event UpdatedImplementation(address indexed implementation); event NewTokenDeployed(address indexed issuer, address token, address proxy); /** * @dev Initialization instead of constructor, called once. Sets BaseOperators contract through pausable contract * resulting in use of Operatorable contract within this contract. * @param _baseOperators BaseOperators contract address. * @param _traderOperators TraderOperators contract address. * @param _blockerOperators BlockerOperators contract address. * @param _whitelist Whitelist contract address. */ function initialize( address _baseOperators, address _traderOperators, address _blockerOperators, address _whitelist, address _implementation, address _proxyAdmin ) public initializer { require(_baseOperators != address(0), "TokenFactory: _baseOperators cannot be set to an empty address"); require(_traderOperators != address(0), "TokenFactory: _traderOperators cannot be set to an empty address"); require(_blockerOperators != address(0), "TokenFactory: _blockerOperators cannot be set to an empty address"); require(_whitelist != address(0), "TokenFactory: _whitelist cannot be set to an empty address"); require(_implementation != address(0), "TokenFactory: _implementation cannot be set to an empty address"); require(_proxyAdmin != address(0), "TokenFactory: _proxyAdmin cannot be set to an empty address"); traderOperators = _traderOperators; blockerOperators = _blockerOperators; whitelist = _whitelist; proxyAdmin = _proxyAdmin; implementation = _implementation; super.initialize(_baseOperators); } /** * @dev allows operator, system or relay to launch a new token with a new name, symbol, decimals, category, and issuer. * Defaults to using whitelist stored in this contract. If _whitelist is address(0), else it will use * _whitelist as the param to pass into the new token's constructor upon deployment * @param _details token details as defined by the TokenDetails struct * @param _whitelist address */ function newToken(Details.TokenDetails memory _details, address _whitelist) public onlyOperatorOrSystemOrRelay returns (address, address) { address whitelistAddress; _whitelist == address(0) ? whitelistAddress = whitelist : whitelistAddress = _whitelist; address baseOperators = getOperatorsContract(); address proxy = ProxyDeployer.deployTokenProxy(implementation, proxyAdmin, ""); TokenDeployer.initializeToken( proxy, baseOperators, whitelistAddress, traderOperators, blockerOperators, _details ); emit NewTokenDeployed(_details.issuer, implementation, proxy); return (implementation, proxy); } /** * @dev updates the whitelist to be used for future generated tokens * @param _whitelist address */ function updateWhitelist(address _whitelist) public onlyOperator { require(_whitelist != address(0), "TokenFactory: _whitelist cannot be set to an empty address"); whitelist = _whitelist; emit UpdatedWhitelist(whitelist); } /** * @dev updates the traderOperators contract address to be used for future generated tokens * @param _traderOperators address */ function updateTraderOperators(address _traderOperators) public onlyOperator { require(_traderOperators != address(0), "TokenFactory: _traderOperators cannot be set to an empty address"); traderOperators = _traderOperators; emit UpdatedTraderOperators(_traderOperators); } /** * @dev updates the blockerOperators contract address to be used for future generated tokens * @param _blockerOperators address */ function updateBlockerOperators(address _blockerOperators) public onlyOperator { require(_blockerOperators != address(0), "TokenFactory: _blockerOperators cannot be set to an empty address"); blockerOperators = _blockerOperators; emit UpdatedBlockerOperators(_blockerOperators); } /** * @dev update the implementation address used when deploying proxy contracts * @param _implementation address */ function updateImplementation(address _implementation) public onlyOperator { require(_implementation != address(0), "TokenFactory: _implementation cannot be set to an empty address"); implementation = _implementation; emit UpdatedImplementation(implementation); } /** * @dev update the proxy admin address used when deploying proxy contracts * @param _proxyAdmin address */ function updateProxyAdmin(address _proxyAdmin) public { require(_proxyAdmin != address(0), "TokenFactory: _proxyAdmin cannot be set to an empty address"); require(msg.sender == proxyAdmin, "TokenFactory: caller not proxy admin"); proxyAdmin = _proxyAdmin; emit UpdatedProxyAdmin(proxyAdmin); } }
Batch mint. _accounts Array of all addresses to mint to. _amounts Array of all values to mint./
function batchMint(address[] memory _accounts, uint256[] memory _amounts) public { require(_accounts.length == _amounts.length, "SygnumToken: values and recipients are not equal."); require(_accounts.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT."); for (uint256 i = 0; i < _accounts.length; i++) { mint(_accounts[i], _amounts[i]); } }
2,088,076
/** *Submitted for verification at Etherscan.io on 2022-01-07 */ //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } library Randoms { function rnd1(uint256 salt, uint16 upperLimit) internal view returns (uint256 r1) { uint256 r = uint256( keccak256( abi.encodePacked( block.timestamp, msg.sender, salt, msg.sender.balance ) ) ); r1 = uint256(r % upperLimit); } function rnd2(uint256 salt, uint16 upperLimit) internal view returns (uint256 r1,uint256 r2) { uint256 r = uint256( keccak256( abi.encodePacked( block.timestamp, msg.sender, salt, msg.sender.balance ) ) ); r1 = uint256(r % upperLimit); r2 = uint256( (r>>16) %upperLimit); } } /** Gold Mask APE */ contract GoldMaskApe is ERC721Enumerable, Ownable { event GoldMaskApeMint(address to, uint256 nftId, uint256 itemData); event SaleTimeChanged( uint256 newPresaleStart, uint256 newPresaleEnd, uint256 newPublicSaleEnd ); using Counters for Counters.Counter; using Strings for uint256; //=======ERC721 BASIC SECTION ====== Counters.Counter private _tokenIdCounter; string private theBaseUrl; //=======ADMIN ADDRESS address private theAdmin; //=======OUR LOGIC SECTION====== mapping(uint256 => uint256) private theItemDataMapping; mapping(address => bool) private theOgList; mapping(address => bool) private theWhiteList; mapping(address => uint256) private theUserBoughtInPresale; uint256 public thePreSaleStartTime; uint256 public thePreSaleEndTime; uint256 public thePublicSaleEndTime; uint256 public constant MAX_SUPPLY = 8192; uint256 public PRESALE_MAX = 2000; uint256 public MARKETING_RESERVE_MAX = 150; uint256 public thePresaleCount; uint256 public theMarketingCount; uint256 public thePublicSaleCount; uint256 public theOgBuyLimit; uint256 public theWhiteListBuyLimit; uint256 public theOgBuyPrice; uint256 public theWhiteListBuyPrice; uint256 public thePublicSalePrice; //MODIFIERS modifier onlyAdminOrOwner() { require( msg.sender == owner() || msg.sender == theAdmin, "ONLY ADMIN OR OWNER CAN CALL THIS METHOD" ); _; } //=======METHODS============= //base url should end with / constructor( string memory nftBaseUrl, address adminAddr, uint256 presaleStartTime, uint256 presaleEndTime, uint256 publicSaleEndTime ) payable ERC721("Gold Mask Ape", "GMA") { theBaseUrl = nftBaseUrl; thePreSaleStartTime = presaleStartTime; thePreSaleEndTime = presaleEndTime; thePublicSaleEndTime = publicSaleEndTime; theAdmin = adminAddr; theOgBuyPrice = 0.06 ether; theWhiteListBuyPrice = 0.06 ether; thePublicSalePrice = 0.08 ether; theOgBuyLimit = 4; theWhiteListBuyLimit = 2; } //======= MINT SECTION ========== function marketingMint(address[] calldata to) public onlyAdminOrOwner { require( (theMarketingCount + to.length) <= MARKETING_RESERVE_MAX, "MARKETING_RESERVE_MAX EXCEEDED" ); theMarketingCount += to.length; for (uint256 i = 0; i < to.length; i++) { _mintOne(to[i], i); } } function buy(uint256 count) public payable { require(inSalePeriod(), "NOT IN SALE"); require(count > 0, "CAN'T BUY 0"); require(count <= queryLeft(), "SOLD OUT"); if (inPresale()) { //IN PRESALE PERIOD if (theOgList[msg.sender]) { require( theUserBoughtInPresale[msg.sender] + count <= theOgBuyLimit, "EXCEEDED" ); } else if (theWhiteList[msg.sender]) { require( theUserBoughtInPresale[msg.sender] + count <= theWhiteListBuyLimit, "EXCEEDED" ); } else { revert("PLEASE WAIT FOR PUBLIC SALE"); } thePresaleCount += count; theUserBoughtInPresale[msg.sender] += count; _buy(count); } if (inPublicSale()) { thePublicSaleCount += count; _buy(count); return; } } function _buy(uint256 count) private { uint256 finalPrice = queryPrice(count); require( msg.value == finalPrice, "MSG.VALUE DOESN'T MATCH REQUIRED VALUE" ); for (uint256 i = 0; i < count; i++) { _mintOne(msg.sender, i); } } function _mintOne(address to, uint256 seed) private { //avoid hash salt collision uint256 scaledSeed = seed * 10; uint256 data = genData(scaledSeed); _mintWithData(to, data); } function genData(uint256 seed) public view returns (uint256) { uint256 data = 0; //7 parts for (uint256 i = 0; i < 7; i++) { data |= genPart(i, seed + i); } return data; } function _mintWithData(address to, uint256 itemData) private { uint256 tokenIdCurrent = _tokenIdCounter.current(); _safeMint(to, _tokenIdCounter.current()); theItemDataMapping[_tokenIdCounter.current()] = itemData; _tokenIdCounter.increment(); emit GoldMaskApeMint(to, tokenIdCurrent, itemData); } //======= MINT SECTION ENDS========== //=======ADMIN OP================= function addWhiteList(address[] calldata newWhiteList) public onlyAdminOrOwner { for (uint256 i = 0; i < newWhiteList.length; i++) { theWhiteList[newWhiteList[i]] = true; } } function addOGList(address[] calldata newOGList) public onlyAdminOrOwner { for (uint256 i = 0; i < newOGList.length; i++) { theOgList[newOGList[i]] = true; } } function setBaseUrl(string calldata newBaseUrl) public onlyAdminOrOwner { theBaseUrl = newBaseUrl; } function setOGPrice(uint256 newPrice) public onlyAdminOrOwner { require(newPrice >= 10**10); theOgBuyPrice = newPrice; } function setWhiteListPrice(uint256 newPrice) public onlyAdminOrOwner { require(newPrice >= 10**10); theWhiteListBuyPrice = newPrice; } function setPublicSalePrice(uint256 newPrice) public onlyAdminOrOwner { require(newPrice >= 10**10); thePublicSalePrice = newPrice; } function setSaleTime( uint256 presaleStart, uint256 presaleEnd, uint256 publicSaleEnd ) public onlyAdminOrOwner { thePreSaleStartTime = presaleStart; thePreSaleEndTime = presaleEnd; thePublicSaleEndTime = publicSaleEnd; emit SaleTimeChanged(presaleStart, presaleEnd, publicSaleEnd); } function setPresaleMax(uint256 newPreSaleMax) public onlyAdminOrOwner { require( newPreSaleMax >= thePresaleCount, "NEW PRESALE MAX SHOULD BE MORE THAN SOLD COUNT" ); PRESALE_MAX = newPreSaleMax; } function takeOutNativeToken(address payable to, uint256 amount) public onlyOwner { require(amount <= address(this).balance, "INSUFFICIENT BALANCE"); (bool sent, bytes memory data) = to.call{value: amount}(""); require(sent, "TRANSFER OUT NATIVE TOKEN FAILED"); } function setAdminAddress(address newAdmin) public onlyOwner { theAdmin = newAdmin; } //=======ADMIN OP ENDS================= //=========VIEWS================== function inPresale() private view returns (bool) { return block.timestamp >= thePreSaleStartTime && block.timestamp < thePreSaleEndTime; } function inPublicSale() private view returns (bool) { return block.timestamp >= thePreSaleEndTime && block.timestamp < thePublicSaleEndTime; } function inSalePeriod() private view returns (bool) { return block.timestamp >= thePreSaleStartTime && block.timestamp < thePublicSaleEndTime; } function queryBuyableCount() public view returns (uint256) { if (inPresale()) { if (theOgList[msg.sender]) { return theOgBuyLimit > theUserBoughtInPresale[msg.sender] ? theOgBuyLimit - theUserBoughtInPresale[msg.sender] : 0; } if (theWhiteList[msg.sender]) { return theWhiteListBuyLimit > theUserBoughtInPresale[msg.sender] ? theWhiteListBuyLimit - theUserBoughtInPresale[msg.sender] : 0; } } if (inPublicSale()) { return queryLeft(); } return 0; } function queryUserTyp(address user) public view returns (uint256) { // 0 FOR NORMAL // 1 FOR OG // 2 FOR WHITE LIST if (theOgList[user]) { return 1; } if (theWhiteList[user]) { return 2; } return 0; } function queryLeft() public view returns (uint256) { if (block.timestamp < thePreSaleStartTime) { return MAX_SUPPLY; } if (inPresale()) { return PRESALE_MAX - thePresaleCount; } if (inPublicSale()) { return MAX_SUPPLY - MARKETING_RESERVE_MAX - thePresaleCount - thePublicSaleCount; } return 0; } function queryPrice(uint256 count) public view returns (uint256 finalPrice) { uint256 thePrice; if (block.timestamp <= thePreSaleEndTime) { //before Presale period ends if (theOgList[msg.sender]) { thePrice = theOgBuyPrice; } else if (theWhiteList[msg.sender]) { thePrice = theWhiteListBuyPrice; } else { thePrice = thePublicSalePrice; } } else { thePrice = thePublicSalePrice; } finalPrice = thePrice * count; } function _baseURI() internal view override returns (string memory) { return theBaseUrl; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return string( abi.encodePacked( baseURI, tokenId.toString(), "/", theItemDataMapping[tokenId].toString() ) ); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function getAllTokenIdAndDataByAddress(address user) public view returns (uint256[] memory) { uint256 userBalance = balanceOf(user); uint256[] memory result = new uint256[](userBalance * 2); for (uint256 i = 0; i < userBalance; i++) { result[i * 2] = tokenOfOwnerByIndex(user, i); result[i * 2 + 1] = theItemDataMapping[ tokenOfOwnerByIndex(user, i) ]; } return result; } function getDataByNftId(uint256 nftId) public view returns (uint256) { return theItemDataMapping[nftId]; } function genPart(uint256 partPos, uint256 rndSeed) public view returns (uint256) { uint256 r1; uint256 r2; (r1, r2) = Randoms.rnd2(rndSeed, 100); uint256 partTyp = 0; uint256 partColor = 0; if (partPos == 0) { if (r1 >= 0 && r1 < 100) { partTyp = 0; } if (r2 >= 0 && r2 < 60) { partColor = 0; } else if (r2 >= 60 && r2 < 80) { partColor = 1; } else if (r2 >= 80 && r2 < 90) { partColor = 2; } else if (r2 >= 90 && r2 < 94) { partColor = 3; } else if (r2 >= 94 && r2 < 97) { partColor = 4; } else if (r2 >= 97 && r2 < 99) { partColor = 5; } else if (r2 >= 99 && r2 < 100) { partColor = 6; } } else if ( partPos == 1 || partPos == 2 || partPos == 3 || partPos == 5 || partPos == 6 ) { if (r1 >= 0 && r1 < 25) { partTyp = 0; } else if (r1 >= 25 && r1 < 50) { partTyp = 1; } else if (r1 >= 50 && r1 < 70) { partTyp = 2; } else if (r1 >= 70 && r1 < 85) { partTyp = 3; } else if (r1 >= 85 && r1 < 95) { partTyp = 4; } else if (r1 >= 95 && r1 < 100) { partTyp = 5; } if (r2 >= 0 && r2 < 25) { partColor = 0; } else if (r2 >= 25 && r2 < 50) { partColor = 1; } else if (r2 >= 50 && r2 < 70) { partColor = 2; } else if (r2 >= 70 && r2 < 85) { partColor = 3; } else if (r2 >= 85 && r2 < 95) { partColor = 4; } else if (r2 >= 95 && r2 < 99) { partColor = 5; } else if (r2 >= 99 && r2 < 100) { partColor = 6; } } else if (partPos == 4) { if (r1 >= 0 && r1 < 100) { partTyp = 0; } if (r2 >= 0 && r2 < 25) { partColor = 0; } else if (r2 >= 25 && r2 < 50) { partColor = 1; } else if (r2 >= 50 && r2 < 70) { partColor = 2; } else if (r2 >= 70 && r2 < 85) { partColor = 3; } else if (r2 >= 85 && r2 < 95) { partColor = 4; } else if (r2 >= 95 && r2 < 99) { partColor = 5; } else if (r2 >= 99 && r2 < 100) { partColor = 6; } } else { revert("UNKNOW BODY PART"); } return (partTyp << (partPos * 8 + 4)) | (partColor << (partPos * 8)); } }
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 ====/ 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.
function _beforeTokenTransfer( address from, address to, uint256 tokenId } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; }
2,452,416
./full_match/1/0x093f6dFaD3c1C29A21CC8A88a8a5eD5A2A67d7B8/sources/Volumes/Data/Projects/Less/lessswap-contracts/contracts/libraries/LessSwapLibrary.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, "LessSwapLibrary: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "LessSwapLibrary: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; }
4,866,852
./full_match/43113/0x3a7D90487F8E6c8631317E1B812d020CE5bB1288/sources/src/LBToken.sol
Returns true if `spender` is approved to transfer `owner`'s tokens or if `spender` is the `owner`. owner The address of the owner. spender The address of the spender. return True if `spender` is approved to transfer `owner`'s tokens./
function _isApprovedForAll(address owner, address spender) internal view returns (bool) { return owner == spender || _spenderApprovals[owner][spender]; }
7,117,390
./full_match/1/0x7FeEe1c7AF002bCfc12720539Bf8360A2f1724DF/sources/bozy.sol
Resumes ICO contribution. Set the state to running.
function resumeICO() public onlyFounder { icoState = State.running; }
3,099,184
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import './interfaces/IERC20.sol'; import './interfaces/ISwitchTicketFactory.sol'; import './interfaces/ISwitchTreasury.sol'; import './libraries/TransferHelper.sol'; import './modules/UserTokenLimit.sol'; import './modules/ReentrancyGuard.sol'; import './modules/Pausable.sol'; import './modules/Initializable.sol'; import './SwitchTicket.sol'; contract SwitchTicketFactory is UserTokenLimit, Pausable, ReentrancyGuard, Initializable { address public weth; address public treasury; address public oldTicketFactory; string public prefixSymbol; string public prefixName; address[] public tickets; address[] public tokens; mapping(address => address) public tokenMap; mapping(address => bool) public tokenStatus; mapping(address => bool) public tokenExistence; mapping(address => bool) public ticketExistence; bool public enableTokenList; struct TokenMapData { address token; address ticket; } event TokenStatusChanged(address indexed token, bool enabled); event TicketCreated(address indexed token, address indexed ticket, string symbol, string name); event Deposited(address indexed _token, address indexed _ticket, address from, address to, uint value); event Withdrawed(address indexed _token, address indexed _ticket, address from, address to, uint _value); event TreasuryChanged(address indexed user, address indexed _old, address indexed _new); event PrefixChanged(address indexed user, string _prefixSymbol, string _prefixName); event OldTicketFactoryChanged(address indexed user, address indexed _old, address indexed _new); event EnableTokenListChanged(address indexed user, bool indexed _old, bool indexed _new); receive() external payable { } function initialize(address _weth) external initializer { require(_weth != address(0), 'SwitchTicketFactory: ZERO_ADDRESS'); owner = msg.sender; weth = _weth; } function pause() external onlyManager whenNotPaused { _pause(); } function unpause() external onlyManager whenPaused { _unpause(); } function countTicket() public view returns (uint) { return tickets.length; } function countToken() public view returns (uint) { return tokens.length; } function configure(address _treasury, bool _value, string calldata _prefixSymbol, string calldata _prefixName) external onlyDev { require(_treasury != address(0), 'SwitchTicketFactory: ZERO_ADDRESS'); emit TreasuryChanged(msg.sender, treasury, _treasury); emit PrefixChanged(msg.sender, _prefixSymbol, _prefixName); treasury = _treasury; enableTokenList = _value; prefixSymbol = _prefixSymbol; prefixName = _prefixName; } function setTreasury(address _treasury) external onlyDev { require(_treasury != address(0), 'SwitchTicketFactory: ZERO_ADDRESS'); emit TreasuryChanged(msg.sender, treasury, _treasury); treasury = _treasury; } function setPrefix(string calldata _prefixSymbol, string calldata _prefixName) external onlyDev { emit PrefixChanged(msg.sender, _prefixSymbol, _prefixName); prefixSymbol = _prefixSymbol; prefixName = _prefixName; } function setOldTicketFactory(address _oldTicketFactory) external onlyDev { require(oldTicketFactory != _oldTicketFactory && _oldTicketFactory != address(this), 'SwitchTicketFactory: INVALID_PARAM'); emit OldTicketFactoryChanged(msg.sender, oldTicketFactory, _oldTicketFactory); oldTicketFactory = _oldTicketFactory; } function getTokenMap(address _token) public view returns (address) { if (_token == address(0)) { _token = weth; } address res = tokenMap[_token]; if(res == address(0) && oldTicketFactory != address(0)) { res = ISwitchTicketFactory(oldTicketFactory).getTokenMap(_token); } return res; } function isTicket(address _ticket) public view returns (bool) { bool res = ticketExistence[_ticket]; if(res == false && oldTicketFactory != address(0)) { res = ISwitchTicketFactory(oldTicketFactory).isTicket(_ticket); } return res; } function enableToken(bool _value) external onlyDev { emit EnableTokenListChanged(msg.sender, enableTokenList, _value); enableTokenList = _value; } function setToken(address _token, bool _value) public onlyDev { if(tokenExistence[_token] == false) { tokens.push(_token); tokenExistence[_token] = true; } tokenStatus[_token] = _value; emit TokenStatusChanged(_token, _value); } function setTokens(address[] memory _tokens, bool[] memory _values) external onlyDev { require(_tokens.length == _values.length, 'SwitchTicketFactory: INVALID_PARAM'); for (uint i; i < _tokens.length; i++) { setToken(_tokens[i], _values[i]); } } function canCreateTicket(address _token) public view returns (bool) { if(_token == address(0)) { _token = weth; } if(enableTokenList) { if(tokenMap[_token] == address(0) && tokenStatus[_token]) { return true; } } else { if(tokenMap[_token] == address(0)) { return true; } } return false; } function createTicket(address _token) public returns (address ticket) { if(_token == address(0)) { _token = weth; } if(enableTokenList) { require(tokenStatus[_token], "SwitchTicketFactory: TOKEN_FORBIDDEN"); } require(tokenMap[_token] == address(0), 'SwitchTicketFactory: EXISTS'); { // check is compatible or not IERC20(_token).decimals(); IERC20(_token).totalSupply(); IERC20(_token).name(); IERC20(_token).symbol(); } bytes memory bytecode = type(SwitchTicket).creationCode; bytes32 salt = keccak256(abi.encodePacked(_token)); assembly { ticket := create2(0, add(bytecode, 32), mload(bytecode), salt) } string memory _symbol = stringConcat(prefixSymbol, IERC20(_token).symbol()); string memory _name = stringConcat(prefixName, IERC20(_token).name()); SwitchTicket(ticket).initialize(treasury, _token, _symbol, _name); tokenMap[_token] = ticket; tokenMap[ticket] = _token; ticketExistence[ticket] = true; tickets.push(ticket); emit TicketCreated(_token, ticket, _symbol, _name); return ticket; } function deposit(address _token, uint _value, address _to) external payable nonReentrant whenNotPaused returns (address) { require(_value > 0, 'SwitchTicketFactory: ZERO'); if(canCreateTicket(_token)) { createTicket(_token); } bool isETH; if(_token == address(0)) { isETH = true; _token = weth; } address ticket = tokenMap[_token]; require(ticket != address(0), 'SwitchTicketFactory: TICKET_NONEXISTS'); uint depositAmount; if (isETH) { _value = msg.value; depositAmount = ISwitchTreasury(treasury).deposit{value: msg.value}(msg.sender, address(0), _value); } else { depositAmount = ISwitchTreasury(treasury).deposit(msg.sender, _token, _value); } require(depositAmount == _value, "SwitchTicketFactory: TREASURY_DEPOSIT_FAIL"); ISwitchTreasury(treasury).mint(ticket, _to, _value); emit Deposited(_token, ticket, msg.sender, _to, _value); return ticket; } function queryWithdrawInfo(address _user, address _ticket) public view returns (uint balance, uint amount) { address _token = tokenMap[_ticket]; balance = IERC20(_ticket).balanceOf(_user); amount = ISwitchTreasury(treasury).queryWithdraw(address(this), _token); if(amount < balance) { amount = balance; } amount = getUserLimit(_user, _token, amount); return (balance, amount); } function queryWithdraw(address _user, address _ticket) public view returns (uint) { (uint balance, uint amount) = queryWithdrawInfo(_user, _ticket); if(amount < balance) { balance = amount; } return balance; } function withdrawAdv(bool isETH, address _to, address _ticket, uint _value) public nonReentrant whenNotPaused returns (bool) { require(_value > 0, 'SwitchTicketFactory: ZERO'); address _token = tokenMap[_ticket]; require(_token != address(0), 'SwitchTicketFactory: NOTFOUND_TICKET'); require(queryWithdraw(msg.sender, _ticket) >= _value, 'SwitchTicketFactory: INSUFFICIENT_BALANCE'); _updateUserTokenLimit(_token, _value); emit Withdrawed(_token, _ticket, msg.sender, _to, _value); ISwitchTreasury(treasury).burn(_ticket, msg.sender, _value); ISwitchTreasury(treasury).withdraw(isETH, _to, _token, _value); return true; } function withdraw(address _to, address _ticket, uint _value) external whenNotPaused returns (bool) { address _token = tokenMap[_ticket]; bool isETH; if(_token == weth) { isETH = true; } return withdrawAdv(isETH, _to, _ticket, _value); } function getTokenMapData(address _ticket) public view returns (TokenMapData memory){ return TokenMapData({ token: tokenMap[_ticket], ticket: _ticket }); } function iterateTokenMapData(uint _start, uint _end) external view returns (TokenMapData[] memory result){ require(_start <= _end && _start >= 0 && _end >= 0, "SwitchTicketFactory: INVAID_PARAMTERS"); uint count = countTicket(); if (_end > count) _end = count; count = _end - _start; result = new TokenMapData[](count); if (count == 0) return result; uint index = 0; for(uint i = _start;i < _end;i++) { address _ticket = tickets[i]; result[index] = getTokenMapData(_ticket); index++; } return result; } function stringConcat(string memory _a, string memory _b) public returns (string memory){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ret = new string(_ba.length + _bb.length); bytes memory bret = bytes(ret); uint k = 0; for (uint i = 0; i < _ba.length; i++) bret[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) bret[k++] = _bb[i]; return string(ret); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface ISwitchTicketFactory { function treasury() external view returns (address); function getTokenMap(address _token) external view returns (address); function isTicket(address _ticket) external view returns (bool); function deposit(address _token, uint _value, address _to) external payable returns (address); function queryWithdrawInfo(address _user, address _ticket) external view returns (uint balance, uint amount); function queryWithdraw(address _user, address _ticket) external view returns (uint); function withdraw(bool isETH, address _to, address _ticket, uint _value) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface ISwitchTreasury { function tokenBalanceOf(address _token) external returns (uint); function mint(address _token, address _to, uint _value) external returns (uint); function burn(address _token, address _from, uint _value) external returns (uint); function deposit(address _from, address _token, uint _value) external payable returns (uint); function queryWithdraw(address _user, address _token) external view returns (uint); function withdraw(bool _isETH, address _to, address _token, uint _value) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; import '../libraries/SafeMath.sol'; import '../modules/Configable.sol'; contract UserTokenLimit is Configable { using SafeMath for uint; struct TokenLimit { bool enabled; uint blocks; uint amount; } //key:(token) mapping(address => TokenLimit) public tokenLimits; struct UserLimit { uint lastBlock; uint consumption; } //key:(white user, token) mapping(address => mapping(address => UserLimit)) public userLimits; function setTokenLimit(address _token, bool _enabled, uint _blocks, uint _amount) public onlyManager { TokenLimit storage limit = tokenLimits[_token]; limit.enabled = _enabled; limit.blocks = _blocks; limit.amount = _amount; } function setTokenLimits(address[] memory _token, bool[] memory _enabled, uint[] memory _blocks, uint[] memory _amount) external onlyManager { require( _token.length == _enabled.length && _enabled.length == _blocks.length && _blocks.length == _amount.length , "UserTokenLimit: INVALID_PARAM" ); for (uint i; i < _token.length; i++) { setTokenLimit(_token[i], _enabled[i], _blocks[i], _amount[i]); } } function setTokenLimitEnable(address _token, bool _enabled) public onlyManager { TokenLimit storage limit = tokenLimits[_token]; limit.enabled = _enabled; } function setTokenLimitEnables(address[] memory _token, bool[] memory _enabled) external onlyManager { require( _token.length == _enabled.length , "UserTokenLimit: INVALID_PARAM" ); for (uint i; i < _token.length; i++) { setTokenLimitEnable(_token[i], _enabled[i]); } } function getUserLimit(address _user, address _token, uint _value) public view returns (uint) { TokenLimit memory tokenLimit = tokenLimits[_token]; if (tokenLimit.enabled == false) { return _value; } if(_value > tokenLimit.amount) { _value = tokenLimit.amount; } UserLimit memory limit = userLimits[_user][_token]; if (block.number.sub(limit.lastBlock) >= tokenLimit.blocks) { return _value; } if (limit.consumption.add(_value) > tokenLimit.amount) { _value = tokenLimit.amount.sub(limit.consumption); } return _value; } function _updateUserTokenLimit(address _token, uint _value) internal { TokenLimit memory tokenLimit = tokenLimits[_token]; if(tokenLimit.enabled == false) { return; } UserLimit storage limit = userLimits[msg.sender][_token]; if(block.number.sub(limit.lastBlock) > tokenLimit.blocks) { limit.consumption = 0; } limit.lastBlock = block.number; limit.consumption = limit.consumption.add(_value); } } // 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 = 0; uint256 private constant _ENTERED = 1; uint256 private _status; /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @dev 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 { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(); bool private _paused; /** * @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() virtual { 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(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import './modules/SwitchERC20.sol'; interface IWETH { function deposit() external payable; function withdraw(uint) external; } contract SwitchTicket is SwitchERC20 { bool initialized; uint public constant version = 1; address public token; address public owner; event OwnerChanged(address indexed _user, address indexed _old, address indexed _new); modifier onlyOwner() { require(msg.sender == owner, 'SwitchTicket: FORBIDDEN'); _; } function initialize(address _owner, address _token, string calldata _symbol, string calldata _name) external { require(!initialized, 'SwitchTicket: initialized'); initialized = true; owner = _owner; token = _token; symbol = _symbol; name = _name; decimals = SwitchERC20(_token).decimals(); } function changeOwner(address _user) external onlyOwner { require(owner != _user, 'SwitchTicket: NO CHANGE'); emit OwnerChanged(msg.sender, owner, _user); owner = _user; } function mint(address to, uint value) external onlyOwner returns (bool) { _mint(to, value); return true; } function burn(address from, uint value) external onlyOwner returns (bool) { _burn(from, value); return true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; interface IConfig { function dev() external view returns (address); function admin() external view returns (address); } contract Configable { address public config; address public owner; event ConfigChanged(address indexed _user, address indexed _old, address indexed _new); event OwnerChanged(address indexed _user, address indexed _old, address indexed _new); function setupConfig(address _config) external onlyOwner { emit ConfigChanged(msg.sender, config, _config); config = _config; } modifier onlyOwner() { require(msg.sender == owner, 'OWNER FORBIDDEN'); _; } function admin() public view returns(address) { if(config != address(0)) { return IConfig(config).admin(); } return owner; } function dev() public view returns(address) { if(config != address(0)) { return IConfig(config).dev(); } return owner; } function changeOwner(address _user) external onlyOwner { require(owner != _user, 'Owner: NO CHANGE'); emit OwnerChanged(msg.sender, owner, _user); owner = _user; } modifier onlyDev() { require(msg.sender == dev() || msg.sender == owner, 'dev FORBIDDEN'); _; } modifier onlyAdmin() { require(msg.sender == admin(), 'admin FORBIDDEN'); _; } modifier onlyManager() { require(msg.sender == dev() || msg.sender == admin() || msg.sender == owner, 'manager FORBIDDEN'); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import '../libraries/SafeMath.sol'; contract SwitchERC20 { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint _chainId; assembly { _chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), _chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { _transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { require(balanceOf[from] >= value, 'SwitchERC20: INSUFFICIENT_BALANCE'); balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); if (to == address(0)) { // burn totalSupply = totalSupply.sub(value); } emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { require(allowance[from][msg.sender] >= value, 'SwitchERC20: INSUFFICIENT_ALLOWANCE'); allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'SwitchERC20: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'SwitchERC20: INVALID_SIGNATURE'); _approve(owner, spender, value); } }
check is compatible or not
function createTicket(address _token) public returns (address ticket) { if(_token == address(0)) { _token = weth; } if(enableTokenList) { require(tokenStatus[_token], "SwitchTicketFactory: TOKEN_FORBIDDEN"); } require(tokenMap[_token] == address(0), 'SwitchTicketFactory: EXISTS'); { IERC20(_token).decimals(); IERC20(_token).totalSupply(); IERC20(_token).name(); IERC20(_token).symbol(); } bytes memory bytecode = type(SwitchTicket).creationCode; bytes32 salt = keccak256(abi.encodePacked(_token)); assembly { ticket := create2(0, add(bytecode, 32), mload(bytecode), salt) } string memory _symbol = stringConcat(prefixSymbol, IERC20(_token).symbol()); string memory _name = stringConcat(prefixName, IERC20(_token).name()); SwitchTicket(ticket).initialize(treasury, _token, _symbol, _name); tokenMap[_token] = ticket; tokenMap[ticket] = _token; ticketExistence[ticket] = true; tickets.push(ticket); emit TicketCreated(_token, ticket, _symbol, _name); return ticket; }
11,987,676
// File: IAllowsProxy.sol pragma solidity >=0.8.4; interface IAllowsProxy { function isProxyActive() external view returns (bool); function proxyAddress() external view returns (address); function isApprovedForProxy(address _owner, address _operator) external view returns (bool); } // File: IFactoryMintable.sol pragma solidity >=0.8.4; interface IFactoryMintable { function factoryMint(uint256 _optionId, address _to) external; function factoryCanMint(uint256 _optionId) external returns (bool); } // File: INFT.sol pragma solidity ^0.8.7; interface INFT{ function mintTo(address recipient) external returns (uint256); function remaining() external view returns (uint256); } // File: Initializable.sol pragma solidity ^0.8.7; /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/Initializable.sol */ contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: EIP712Base.sol pragma solidity ^0.8.7; /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/EIP712Base.sol */ contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string public constant ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712(string memory name) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransactionWithExternalNonce( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV, uint256 userNonce ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: userNonce, from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); require(userNonce == nonces[userAddress]); // increase nonce for user (to avoid re-use) nonces[userAddress] = userNonce.add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: ContextMixin.sol pragma solidity ^0.8.7; /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/ContextMixin.sol */ abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/access/IAccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: FactoryMintable.sol pragma solidity ^0.8.7; abstract contract FactoryMintable is IFactoryMintable, Context { address public tokenFactory; error NotTokenFactory(); error FactoryCannotMint(); modifier onlyFactory() { if (_msgSender() != tokenFactory) { revert NotTokenFactory(); } _; } modifier canMint(uint256 _optionId) { if (!factoryCanMint(_optionId)) { revert FactoryCannotMint(); } _; } function factoryMint(uint256 _optionId, address _to) external virtual override; function factoryCanMint(uint256 _optionId) public view virtual override returns (bool); } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: AllowsConfigurableProxy.sol pragma solidity >=0.8.4; contract OwnableDelegateProxy {} /** * Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract AllowsConfigurableProxy is IAllowsProxy, Ownable { bool internal isProxyActive_; address internal proxyAddress_; constructor(address _proxyAddress, bool _isProxyActive) { proxyAddress_ = _proxyAddress; isProxyActive_ = _isProxyActive; } function setIsProxyActive(bool _isProxyActive) external onlyOwner { isProxyActive_ = _isProxyActive; } function setProxyAddress(address _proxyAddress) public onlyOwner { proxyAddress_ = _proxyAddress; } function proxyAddress() public view override returns (address) { return proxyAddress_; } function isProxyActive() public view override returns (bool) { return isProxyActive_; } function isApprovedForProxy(address owner, address _operator) public view override returns (bool) { if (isProxyActive_ && proxyAddress_ == _operator) { return true; } ProxyRegistry proxyRegistry = ProxyRegistry(proxyAddress_); if ( isProxyActive_ && address(proxyRegistry.proxies(owner)) == _operator ) { return true; } return false; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/access/AccessControl.sol // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: NFTERC721.sol pragma solidity ^0.8.7; contract NFTERC721 is INFT, ERC721, ERC721Burnable, ERC721Pausable, ERC721Enumerable, AccessControl, Ownable, ContextMixin, NativeMetaTransaction { // Create a new role identifier for the minter role bytes32 public constant MINER_ROLE = keccak256("MINER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); using Counters for Counters.Counter; Counters.Counter private currentTokenId; /// @dev Base token URI used as a prefix by tokenURI(). string private baseTokenURI; string private collectionURI; uint256 public constant TOTAL_SUPPLY = 10800; constructor() ERC721("SONNY", "HM-SON") { _initializeEIP712("SONNY"); baseTokenURI = "https://cdn.nftstar.com/hm-son/metadata/"; collectionURI = "https://cdn.nftstar.com/hm-son/meta-son-heung-min.json"; // Grant the contract deployer the default admin role: it will be able to grant and revoke any roles _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINER_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); } function totalSupply() public pure override returns (uint256) { return TOTAL_SUPPLY; } function remaining() public view override returns (uint256) { return TOTAL_SUPPLY - currentTokenId.current(); } function mintTo(address recipient) public override onlyRole(MINER_ROLE) returns (uint256) { uint256 tokenId = currentTokenId.current(); require(tokenId < TOTAL_SUPPLY, "Max supply reached"); currentTokenId.increment(); uint256 newItemId = currentTokenId.current(); _safeMint(recipient, newItemId); return newItemId; } function ownerTokens(address owner) public view returns (uint256[] memory) { uint256 size = ERC721.balanceOf(owner); uint256[] memory items = new uint256[](size); for (uint256 i = 0; i < size; i++) { items[i] = tokenOfOwnerByIndex(owner, i); } return items; } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require( hasRole(PAUSER_ROLE, msgSender()), "NFT: must have pauser role to pause" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require( hasRole(PAUSER_ROLE, msgSender()), "NFT: must have pauser role to unpause" ); _unpause(); } function current() public view returns (uint256) { return currentTokenId.current(); } function contractURI() public view returns (string memory) { return collectionURI; } function setContractURI(string memory _contractURI) public onlyOwner { collectionURI = _contractURI; } /// @dev Returns an URI for a given token ID function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } /// @dev Sets the base token URI prefix. function setBaseTokenURI(string memory _baseTokenURI) public onlyOwner { baseTokenURI = _baseTokenURI; } function transferRoleAdmin(address newDefaultAdmin) external onlyRole(DEFAULT_ADMIN_ROLE) { _setupRole(DEFAULT_ADMIN_ROLE, newDefaultAdmin); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC721, ERC721Enumerable) returns (bool) { return interfaceId == type(INFT).interfaceId || super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC721, ERC721Pausable, ERC721Enumerable) { super._beforeTokenTransfer(from, to, amount); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: NFTFactory.sol pragma solidity ^0.8.7; contract NFTFactory is IERC721, AllowsConfigurableProxy, Pausable, ReentrancyGuard { using Strings for uint256; uint256 public NUM_OPTIONS; /// @notice Base URI for constructing tokenURI values for options. string public optionURI; /// @notice Contract that deployed this factory. FactoryMintable public token; constructor( string memory _baseOptionURI, address _owner, uint256 _numOptions, address _proxyAddress ) AllowsConfigurableProxy(_proxyAddress, true) { token = FactoryMintable(msg.sender); NUM_OPTIONS = _numOptions; optionURI = _baseOptionURI; transferOwnership(_owner); createOptionsAndEmitTransfers(); } error NotOwnerOrProxy(); error InvalidOptionId(); modifier onlyOwnerOrProxy() { if ( _msgSender() != owner() && !isApprovedForProxy(owner(), _msgSender()) ) { revert NotOwnerOrProxy(); } _; } modifier checkValidOptionId(uint256 _optionId) { // options are 1-indexed so check should be inclusive if (_optionId > NUM_OPTIONS) { revert InvalidOptionId(); } _; } modifier interactBurnInvalidOptionId(uint256 _optionId) { _; _burnInvalidOptions(); } /// @notice Sets the nft address for FactoryMintable. function setNFT(address _token) external onlyOwner { token = FactoryMintable(_token); } /// @notice Sets the base URI for constructing tokenURI values for options. function setBaseOptionURI(string memory _baseOptionURI) public onlyOwner { optionURI = _baseOptionURI; } /** @notice Returns a URL specifying option metadata, conforming to standard ERC1155 metadata format. */ function tokenURI(uint256 _optionId) external view returns (string memory) { return string(abi.encodePacked(optionURI, _optionId.toString())); } /** @dev Return true if operator is an approved proxy of Owner */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { return isApprovedForProxy(_owner, _operator); } ///@notice public facing method for _burnInvalidOptions in case state of tokenContract changes function burnInvalidOptions() public onlyOwner { _burnInvalidOptions(); } ///@notice "burn" option by sending it to 0 address. This will hide all active listings. Called as part of interactBurnInvalidOptionIds function _burnInvalidOptions() internal { for (uint256 i = 1; i <= NUM_OPTIONS; ++i) { if (!token.factoryCanMint(i)) { emit Transfer(owner(), address(0), i); } } } /** @notice emit a transfer event for a "burn" option back to the owner if factoryCanMint the optionId @dev will re-validate listings on OpenSea frontend if an option becomes eligible to mint again eg, if max supply is increased */ function restoreOption(uint256 _optionId) external onlyOwner { if (token.factoryCanMint(_optionId)) { emit Transfer(address(0), owner(), _optionId); } } /** @notice Emits standard ERC721.Transfer events for each option so NFT indexers pick them up. Does not need to fire on contract ownership transfer because once the tokens exist, the `ownerOf` check will always pass for contract owner. */ function createOptionsAndEmitTransfers() internal { for (uint256 i = 1; i <= NUM_OPTIONS; i++) { emit Transfer(address(0), owner(), i); } } function approve(address operator, uint256) external override onlyOwner { setProxyAddress(operator); } function getApproved(uint256) external view override returns (address operator) { return proxyAddress(); } function setApprovalForAll(address operator, bool) external override onlyOwner { setProxyAddress(operator); } function supportsFactoryInterface() public pure returns (bool) { return true; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC165).interfaceId; } function balanceOf(address _owner) external view override returns (uint256) { return _owner == owner() ? NUM_OPTIONS : 0; } /** @notice Returns owner if _optionId is valid so posted orders pass validation */ function ownerOf(uint256 _optionId) public view override returns (address) { return token.factoryCanMint(_optionId) ? owner() : address(0); } function safeTransferFrom( address, address _to, uint256 _optionId ) public override nonReentrant onlyOwnerOrProxy whenNotPaused interactBurnInvalidOptionId(_optionId) { token.factoryMint(_optionId, _to); } function safeTransferFrom( address, address _to, uint256 _optionId, bytes calldata ) external override { safeTransferFrom(_to, _to, _optionId); } /** @notice hack: transferFrom is called on sale , this method mints the real token */ function transferFrom( address, address _to, uint256 _optionId ) public override nonReentrant onlyOwnerOrProxy whenNotPaused interactBurnInvalidOptionId(_optionId) { token.factoryMint(_optionId, _to); } } // File: NFTFactoryERC721.sol pragma solidity ^0.8.7; contract NFTFactoryERC721 is NFTERC721, FactoryMintable, ReentrancyGuard, AllowsConfigurableProxy { using Strings for uint256; uint256 public maxSupply; error NewMaxSupplyMustBeGreater(); constructor(address _proxyAddress) AllowsConfigurableProxy(_proxyAddress, true) { maxSupply = totalSupply(); tokenFactory = address( new NFTFactory( "https://cdn.nftstar.com/hm-son-mint/metadata/", owner(), 5, _proxyAddress ) ); _setupRole(MINER_ROLE, tokenFactory); emit Transfer(address(0), owner(), 0); } function factoryMint(uint256 _optionId, address _to) public override nonReentrant onlyFactory canMint(_optionId) { for (uint256 i; i < _optionId; ++i) { mintTo(_to); } } function factoryCanMint(uint256 _optionId) public view virtual override returns (bool) { if (_optionId == 0 || _optionId > maxSupply) { return false; } if (_optionId > (maxSupply - current())) { return false; } return true; } function setMaxSupply(uint256 _maxSupply) public onlyOwner { if (_maxSupply <= maxSupply) { revert NewMaxSupplyMustBeGreater(); } maxSupply = _maxSupply; } }
Emitted when the pause is triggered by `account`./ Emitted when the pause is lifted by `account`./ Initializes the contract in unpaused state./
function factoryMint(uint256 _optionId, address _to) external virtual override; function factoryCanMint(uint256 _optionId) public view virtual override returns (bool); } pragma solidity ^0.8.0; constructor() { _paused = false; }
6,034,610
/// https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code /// Submitted for verification at Etherscan.io on 2017-11-28 pragma solidity ^0.4.11; /// 所有者合约拥有一个所有者,提供基本的授权控制函数,简化的用户权限的实现 contract Ownable { address public owner; // 所有者地址 /// 构造函数设置所有者 function Ownable() { owner = msg.sender; } /// 修改器前置验证所有权 modifier onlyOwner() { require(msg.sender == owner); _; } /// 转移所有权函数,要求当前所有者调用 /// 传入新的所有者地址 非 0 地址 function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// ERC721 NFT 代币接口 Non-Fungible Tokens contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom( address _from, address _to, uint256 _tokenId ) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); /// ERC165 提供函数检查是否实现了某函数 // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// what? 基因科学接口 contract GeneScienceInterface { /// 是否实现了基因科学? function isGeneScience() public pure returns (bool); /// 混合基因 母猫基因 公猫基因 目标块? -> 下一代基因 function mixGenes( uint256 genes1, uint256 genes2, uint256 targetBlock ) public returns (uint256); } /// 管理特殊访问权限的门面 contract KittyAccessControl { // 4 个角色 // CEO 角色 任命其他角色 改变依赖的合约的地址 唯一可以停止加密猫的角色 在合约初始化时设置 // CFO 角色 可以从机密猫和它的拍卖合约中提出资金 // COO 角色 可以释放第 0 代加密猫 创建推广猫咪 // 这些权限被详细的分开。虽然 CEO 可以给指派任何角色,但 CEO 并不能够直接做这些角色的工作。 // 并非有意限制,而是尽量少使用 CEO 地址。使用的越少,账户被破坏的可能性就越小。 /// 合约升级事件 event ContractUpgrade(address newContract); // 每种角色的地址,也有可能是合约的地址. address public ceoAddress; address public cfoAddress; address public cooAddress; // 保持关注变量 paused 是否为真,一旦为真,大部分操作是不能够实行的 bool public paused = false; /// 修改器仅限 CEO modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// 修改器仅限 CFO modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// 修改器仅限 COO modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// 修改器仅限管理层(CEO 或 CFO 或 COO) modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// 设置新的 CEO 地址 仅限 CEO 操作 function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// 设置新的 CFO 地址 仅限 CEO 操作 function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// 设置新的 COO 地址 仅限 CEO 操作 function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } // OpenZeppelin 提供了很多合约方便使用,每个都应该研究一下 /*** Pausable functionality adapted from OpenZeppelin ***/ /// 修改器仅限没有停止合约 modifier whenNotPaused() { require(!paused); _; } /// 修改器仅限已经停止合约 modifier whenPaused() { require(paused); _; } /// 停止函数 仅限管理层 未停止时 调用 /// 在遇到 bug 或者 检测到非法牟利 这时需要限制损失 /// 仅可外部调用 function pause() external onlyCLevel whenNotPaused { paused = true; } /// 开始合约 仅限 CEO 已经停止时 调用 /// 不能给 CFO 或 COO 权限,因为万一他们账户被盗。 /// 注意这个方法不是外部的,公开表明可以被子合约调用 function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded // what? 如果合约升级了,不能被停止?? paused = false; } } /// 加密猫的基合约 包含所有普通结构体 事件 和 基本变量 contract KittyBase is KittyAccessControl { /*** EVENTS ***/ /// 出生事件 /// giveBirth 方法触发 /// 第 0 代猫咪被创建也会被触发 event Birth( address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes ); /// 转账事件是 ERC721 定义的标准时间,这里猫咪第一次被赋予所有者也会触发 event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// 猫咪的主要结构体,加密猫里的每个猫都要用这个结构体表示。务必确保这个结构体使用 2 个 256 位的字数。 /// 由于以太坊自己包装跪着,这个结构体中顺序很重要(改动就不满足 2 个 256 要求了) struct Kitty { // 猫咪的基因是 256 位,格式是 sooper-sekret 不知道这是什么格式?? uint256 genes; // 出生的时间戳 uint64 birthTime; // 这只猫可以再次进行繁育活动的最小时间戳 公猫和母猫都用这个时间戳 冷却时间?! uint64 cooldownEndBlock; // 下面 ID 用于记录猫咪的父母,对于第 0 代猫咪,设置为 0 // 采用 32 位数字,最大仅有 4 亿多点,目前够用了 截止目前 2021-09-26 有 200 万个猫咪了 uint32 matronId; uint32 sireId; // 母猫怀孕的话,设置为公猫的 id,否则是 0。非 0 表明猫咪怀孕了。 // 当新的猫出生时需要基因物质。 uint32 siringWithId; // 当前猫咪的冷却时间,是冷却时间数组的序号。第 0 代猫咪开始为 0,其他的猫咪是代数除以 2,每次成功繁育后都要自增 1 uint16 cooldownIndex; // 代数 直接由合约创建出来的是第 0 代,其他出生的猫咪由父母最大代数加 1 uint16 generation; } /*** 常量 ***/ /// 冷却时间查询表 /// 设计目的是鼓励玩家不要老拿一只猫进行繁育 /// 最大冷却时间是一周 uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // 目前每个块之间的时间间隔估计 uint256 public secondsPerBlock = 15; /*** 存储 ***/ /// 所有猫咪数据的列表 ID 就是猫咪在这个列表的序号 /// id 为 0 的猫咪是神秘生物,生育了第 0 代猫咪 Kitty[] kitties; /// 猫咪 ID 对应所有者的映射,第 0 代猫咪也有 mapping(uint256 => address) public kittyIndexToOwner; //// 所有者对拥有猫咪数量的映射 是 ERC721 接口 balanceOf 的底层数据支持 mapping(address => uint256) ownershipTokenCount; /// 猫咪对应的授权地址,授权地址可以取得猫咪的所有权 对应 ERC721 接口 transferFrom 方法 mapping(uint256 => address) public kittyIndexToApproved; /// 猫咪对应授权对方可以进行繁育的数据结构 对方可以通过 breedWith 方法进行猫咪繁育 mapping(uint256 => address) public sireAllowedToAddress; /// 定时拍卖合约的地址 点对点销售的合约 也是第 0 代猫咪每 15 分钟初始化的地方 SaleClockAuction public saleAuction; /// 繁育拍卖合约地址 需要和销售拍卖分开 二者有很大区别,分开为好 SiringClockAuction public siringAuction; /// 内部给予猫咪所有者的方法 仅本合约可用 what?感觉这个方法子类应该也可以调用啊??? function _transfer( address _from, address _to, uint256 _tokenId ) internal { // Since the number of kittens is capped to 2^32 we can't overflow this // 对应地址所拥有的数量加 1 ownershipTokenCount[_to]++; // 设置所有权 kittyIndexToOwner[_tokenId] = _to; // 第 0 代猫咪最开始没有 from,后面才会有 if (_from != address(0)) { // 如果有所有者 // 所有者猫咪数量减 1 ownershipTokenCount[_from]--; // 该猫咪设置过的允许繁育的地址删除 不能被上一个所有者设置的别人可以繁育继续有效 delete sireAllowedToAddress[_tokenId]; // 该猫咪设置过的允许授权的地址删除 不能被上一个所有者设置的别人可以拿走继续有效 delete kittyIndexToApproved[_tokenId]; } // 触发所有权变更事件,第 0 代猫咪创建之后,也会触发事件 Transfer(_from, _to, _tokenId); } /// 创建猫咪并存储的内部方法 不做权限参数检查,必须保证传入参数是正确的 会触发出生和转移事件 /// @param _matronId 母猫 id 第 0 代的话是 0 /// @param _sireId 公猫 id 第 0 代的话是 0 /// @param _generation 代数,必须先计算好 /// @param _genes 基因 /// @param _owner 初始所有者 (except for the unKitty, ID 0) function _createKitty( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint256) { // 这些检查是非严格检查,调用这应当确保参数是有效的,本方法依据是个非常昂贵的调用,不要再耗费 gas 检查参数了 require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // 新猫咪的冷却序号是代数除以 2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Kitty memory _kitty = Kitty({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newKittenId = kitties.push(_kitty) - 1; // 确保是 32 位id require(newKittenId == uint256(uint32(newKittenId))); // 触发出生事件 Birth( _owner, newKittenId, uint256(_kitty.matronId), uint256(_kitty.sireId), _kitty.genes ); // 触发所有权转移事件 _transfer(0, _owner, newKittenId); return newKittenId; } /// 设置估计的每个块间隔,这里检查必须小于 1 分钟了 /// 必须管理层调用 外部函数 function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// 外部合约 返回猫咪的元数据 只有一个方法返回字节数组数据 contract ERC721Metadata { /// 给 id 返回字节数组数据,能转化为字符串 /// what? 这都是写死的数据,不知道有什么用 function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// 加密猫核心合约的门面 管理权限 contract KittyOwnership is KittyBase, ERC721 { /// ERC721 接口 string public constant name = "CryptoKitties"; string public constant symbol = "CK"; // 元数据合约 ERC721Metadata public erc721Metadata; /// 方法签名常量,ERC165 要求的方法 bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); /// ERC721 要求的方法签名 /// 字节数组的 ^ 运算时什么意思?? /// 我明白了,ERC721 是一堆方法,不用一各一个验证,这么多方法一起合成一个值,这个值有就行了 bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")) ^ bytes4(keccak256("tokensOfOwner(address)")) ^ bytes4(keccak256("tokenMetadata(uint256,string)")); /// 实现 ERC165 的方法 function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// 设置元数据合约地址,原来这个地址是可以修改的,那么就可以更新了 仅限 CEO 修改 function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } /// 内部工具函数,这些函数被假定输入参数是有效的。 参数校验留给公开方法处理。 /// 检查指定地址是否拥有某只猫咪 内部函数 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToOwner[_tokenId] == _claimant; } /// 检查某只猫咪收被授权给某地址 内部函数 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToApproved[_tokenId] == _claimant; } /// 猫咪收被授权给地址 这样该地址就能够通过 transferFrom 方法取得所有权 内部函数 /// 同一时间只允许有一个授权地址,如果地址是 0 的话,表示清除授权 /// 该方法不触发事件,故意不触发事件。当前方法和transferFrom方法一起在拍卖中使用,拍卖触发授权事件没有意义。 function _approve(uint256 _tokenId, address _approved) internal { kittyIndexToApproved[_tokenId] = _approved; } /// 返回某地址拥有的数量 这也是 ERC721 的方法 function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// 转移猫咪给其他地址 修改器检查只在非停止状态下允许转移 外部函数 /// 如果是转移给其他合约的地址,请清楚行为的后果,否则有可能永久失去这只猫咪 function transfer(address _to, uint256 _tokenId) external whenNotPaused { // 要求地址不为 0 require(_to != address(0)); /// 禁止转移给加密猫合约地址 本合约地址不应该拥有任何一只猫咪 除了再创建第 0 代并且还没进入拍卖的时候 require(_to != address(this)); /// 禁止转移给销售拍卖和繁育拍卖地址,销售拍卖对加密猫的所有权仅限于通过 授权 和 transferFrom 的方式 require(_to != address(saleAuction)); require(_to != address(siringAuction)); // 要求调用方拥有这只猫咪 require(_owns(msg.sender, _tokenId)); // 更改所有权 清空授权 触发转移事件 _transfer(msg.sender, _to, _tokenId); } /// 授权给其他地址 修改器检查只在非停止状态下允许 外部函数 /// 其他合约可以通过transferFrom取得所有权。这个方法被期望在授权给合约地址,参入地址为 0 的话就表明清除授权 /// ERC721 要求方法 function approve(address _to, uint256 _tokenId) external whenNotPaused { // 要求调用方拥有这只猫咪 require(_owns(msg.sender, _tokenId)); // 进行授权 _approve(_tokenId, _to); // 触发授权事件 Approval(msg.sender, _to, _tokenId); } /// 取得猫咪所有权 修改器检查只在非停止状态下允许 外部函数 /// ERC721 要求方法 function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // 检查目标地址不是 0 require(_to != address(0)); // 禁止转移给当前合约 require(_to != address(this)); // 检查调用者是否有被授权,猫咪所有者地址是否正确 require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // 更改所有权 清空授权 触发转移事件 _transfer(_from, _to, _tokenId); } /// 目前所有猫咪数量 公开方法 只读 /// ERC721 要求方法 function totalSupply() public view returns (uint256) { return kitties.length - 1; } /// 查询某只猫咪的所有者 外部函数 只读 /// ERC721 要求方法 function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = kittyIndexToOwner[_tokenId]; require(owner != address(0)); } /// 返回某地址拥有的所有猫咪 id 列表 外部函数 只读 /// 这个方法不应该被合约调用,因为太消耗 gas /// 这方法返回一个动态数组,仅支持 web3 调用,不支持合约对合约的调用 function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // 返回空数组 return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCats = totalSupply(); uint256 resultIndex = 0; // 遍历所有的猫咪如果地址相符就记录 uint256 catId; for (catId = 1; catId <= totalCats; catId++) { if (kittyIndexToOwner[catId] == _owner) { result[resultIndex] = catId; resultIndex++; } } return result; } } /// 内存拷贝方法 function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private view { // Copy word-length chunks while possible // 32 位一块一块复制 for (; _len >= 32; _len -= 32) { assembly { // 取出原地址 放到目标地址 mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes // what? 剩下的部分看不明白了 这个指数运算啥意思啊 uint256 mask = 256**(32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// 转换成字符串 function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { // 先得到指定长度的字符串 var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { // what? 这是取出指定变量的地址?? outputPtr := add(outputString, 32) // 为啥这个就直接当地址用了?? bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// 返回指定猫咪的元数据 包含 URI 信息 function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { // 要求元数据合约地址指定 require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata( _tokenId, _preferredTransport ); return _toString(buffer, count); } } /// 加密猫核心合约的门面 管理猫咪生育 妊娠 和 出生 contract KittyBreeding is KittyOwnership { /// 怀孕事件 当 2 只猫咪成功的饲养并怀孕 event Pregnant( address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock ); /// 自动出生费? breedWithAuto方法使用,这个费用会在 giveBirth 方法中转变成 gas 消耗 /// 可以被 COO 动态更新 uint256 public autoBirthFee = 2 finney; // 怀孕的猫咪计数 uint256 public pregnantKitties; /// 基于科学 兄弟合约 实现基因混合算法,, GeneScienceInterface public geneScience; /// 设置基因合约 仅限 CEO 调用 function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); require(candidateContract.isGeneScience()); // 要求是基因科学合约 geneScience = candidateContract; } /// 检查猫咪是否准备好繁育了 内部函数 只读 要求冷却时间结束 function _isReadyToBreed(Kitty _kit) internal view returns (bool) { // 额外检查冷却结束的块 我们同样需要建擦猫咪是否有等待出生?? 在猫咪怀孕结束和出生事件之间存在一些时间周期??莫名其妙 // In addition to checking the cooldownEndBlock, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); } /// 检查公猫是否授权和这个母猫繁育 内部函数 只读 如果是同一个所有者,或者公猫已经授权给母猫的地址,返回 true function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = kittyIndexToOwner[_matronId]; address sireOwner = kittyIndexToOwner[_sireId]; return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// 设置猫咪的冷却时间 基于当前冷却时间序号 同时增加冷却时间序号除非达到最大序号 内部函数 function _triggerCooldown(Kitty storage _kitten) internal { // 计算估计冷却的块 _kitten.cooldownEndBlock = uint64( (cooldowns[_kitten.cooldownIndex] / secondsPerBlock) + block.number ); // 繁育序号加一 最大是 13,冷却时间数组的最大长度,本来也可以数组的长度,但是这里硬编码进常量,为了节省 gas 费 if (_kitten.cooldownIndex < 13) { _kitten.cooldownIndex += 1; } } /// 授权繁育 外部函数 仅限非停止状态 /// 地址是将要和猫咪繁育的猫咪的所有者 设置 0 地址表明取消繁育授权 function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); // 检查猫咪所有权 sireAllowedToAddress[_sireId] = _addr; // 记录允许地址 } /// 设置自动出生费 外部函数 仅限 COO function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// 是否准备好出生 私有 只读 function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// 检查猫咪是否准备好繁育 公开 只读 function isReadyToBreed(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); Kitty storage kit = kitties[_kittyId]; return _isReadyToBreed(kit); } /// 是否猫咪怀孕了 公开 只读 function isPregnant(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); // 如果 siringWithId 被设置了表明就是怀孕了 return kitties[_kittyId].siringWithId != 0; } /// 内部检查公猫和母猫是不是个有效对 不检查所有权 function _isValidMatingPair( Kitty storage _matron, uint256 _matronId, Kitty storage _sire, uint256 _sireId ) private view returns (bool) { // 不能是自己 if (_matronId == _sireId) { return false; } // 母猫的妈妈不能是公猫 母猫的爸爸不能是公猫 if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } // 公猫的妈妈不能是母猫 公猫的爸爸不能是母猫 if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // 如果公猫或母猫的妈妈是第 0 代猫咪,允许繁育 // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // 讲真我对加密猫的血缘检查无语了,什么乱七八糟的 // 猫咪不能与带血缘关系的繁育,同妈妈 或 公猫的妈妈和母猫的爸爸是同一个 if ( _sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId ) { return false; } // 同爸爸 或 公猫的爸爸和母猫的妈妈是同一个 if ( _sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId ) { return false; } // Everything seems cool! Let's get DTF. return true; } /// 内部检查是否可以通过拍卖进行繁育 function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// 检查 2 只猫咪是否可以繁育 外部函数 只读 检查所有权授权 不检查猫咪是否准备好繁育 在冷却时间期间是不能繁育成功的 function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns (bool) { require(_matronId > 0); require(_sireId > 0); Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } /// 内部工具函数初始化繁育 假定所有的繁育要求已经满足 内部函数 function _breedWith(uint256 _matronId, uint256 _sireId) internal { // 获取猫咪信息 Kitty storage sire = kitties[_sireId]; Kitty storage matron = kitties[_matronId]; // 标记母猫怀孕 指向公猫 matron.siringWithId = uint32(_sireId); // 设置冷却时间 _triggerCooldown(sire); _triggerCooldown(matron); // 情况授权繁育地址,似乎多次一句,这里可以避免困惑 // tips 如果别人指向授权给某个人。每次繁育后还要继续设置,岂不是很烦躁 delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // 怀孕的猫咪计数加 1 pregnantKitties++; // 触发怀孕事件 Pregnant( kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock ); } /// 自动哺育一个猫咪 外部函数 可支付 仅限非停止状态 /// 哺育一个猫咪 作为母猫提供者,和公猫提供者 或 被授权的公猫 /// 猫咪是否会怀孕 或 完全失败 要看 giveBirth 函数给与的预支付的费用 function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { require(msg.value >= autoBirthFee); // 要求大于自动出生费 require(_owns(msg.sender, _matronId)); // 要求是母猫所有者 // 哺育操作期间 允许猫咪被拍卖 拍卖的事情这里不关心 // 对于母猫:这个方法的调用者不会是母猫的所有者,因为猫咪的所有者是拍卖合约 拍卖合约不会调用繁育方法 // 对于公猫:统一,公猫也属于拍卖合约,转移猫咪会清除繁育授权 // 因此我们不花费 gas 费检查猫咪是否属于拍卖合约 // 检查猫咪是否都属于调用者 或 公猫是给与授权的 require(_isSiringPermitted(_sireId, _matronId)); Kitty storage matron = kitties[_matronId]; // 获取母猫信息 require(_isReadyToBreed(matron)); // 确保母猫不是怀孕状态 或者 哺育冷却期 Kitty storage sire = kitties[_sireId]; // 获取公猫信息 require(_isReadyToBreed(sire)); // 确保公猫不是怀孕状态 或者 哺育冷却期 require(_isValidMatingPair(matron, _matronId, sire, _sireId)); // 确保猫咪是有效的匹配 _breedWith(_matronId, _sireId); // 进行繁育任务 } /// 已经有怀孕的猫咪 才能 出生 外部函数 仅限非暂停状态 /// 如果怀孕并且妊娠时间已经过了 联合基因创建一个新的猫咪 /// 新的猫咪所有者是母猫的所有者 /// 知道成功的结束繁育,公猫和母猫才会进入下个准备阶段 /// 注意任何人可以调用这个方法 只要他们愿意支付 gas 费用 但是新猫咪仍然属于母猫的所有者 function giveBirth(uint256 _matronId) external whenNotPaused returns (uint256) { Kitty storage matron = kitties[_matronId]; // 获取母猫信息 require(matron.birthTime != 0); // 要求母猫是有效的猫咪 // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // 要求母猫准备好生猫咪 是怀孕状态并且时间已经到了 uint256 sireId = matron.siringWithId; // 公猫 id Kitty storage sire = kitties[sireId]; // 公猫信息 uint16 parentGen = matron.generation; // 母猫代数 if (sire.generation > matron.generation) { parentGen = sire.generation; // 如果公猫代数高,则用公猫代数 } // 调用混合基因的方法 uint256 childGenes = geneScience.mixGenes( matron.genes, sire.genes, matron.cooldownEndBlock - 1 ); // 制作新猫咪 address owner = kittyIndexToOwner[_matronId]; uint256 kittenId = _createKitty( _matronId, matron.siringWithId, parentGen + 1, childGenes, owner ); delete matron.siringWithId; // 清空母猫的配对公猫 id pregnantKitties--; // 每次猫咪出生,计数器减 1 msg.sender.send(autoBirthFee); // 支付给调用方自动出生费用 return kittenId; // 返回猫咪 id } } /// 定时拍卖核心 包含 结构 变量 内置方法 contract ClockAuctionBase { // 一个 NFT 拍卖的表示 struct Auction { // NFT 当前所有者 address seller; // 开始拍卖的价格 单位 wei uint128 startingPrice; // 结束买卖的价格 单位 wei uint128 endingPrice; // 拍卖持续时间 单位秒 uint64 duration; // 拍卖开始时间 如果是 0 表示拍卖已经结束 uint64 startedAt; } // 关联的 NFT 合约 ERC721 public nonFungibleContract; // 每次拍卖收税 0-10000 对应这 0%-100% uint256 public ownerCut; // 每只猫对应的拍卖信息 mapping(uint256 => Auction) tokenIdToAuction; /// 拍卖创建事件 event AuctionCreated( uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration ); /// 拍卖成功事件 event AuctionSuccessful( uint256 tokenId, uint256 totalPrice, address winner ); /// 拍卖取消事件 event AuctionCancelled(uint256 tokenId); /// 某地址是否拥有某只猫咪 内部函数 只读 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// 托管猫咪 将猫咪托管给当前拍卖合约 function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// NFT 转账 内部函数 function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// 增加拍卖 触发拍卖事件 内部函数 function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; // 触发拍卖创建事件 AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// 取消拍卖 触发取消事件 内部函数 function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// 计算价格并转移 NFT 给胜者 内部函数 function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // 获取拍卖数据 Auction storage auction = tokenIdToAuction[_tokenId]; // 要求拍卖属于激活状态 require(_isOnAuction(auction)); // 要求出价不低于当前价格 uint256 price = _currentPrice(auction); require(_bidAmount >= price); // 获取卖家地址 address seller = auction.seller; // 移除这个猫咪的拍卖 _removeAuction(_tokenId); // 转账给卖家 if (price > 0) { // 计算拍卖费用 uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // 进行转账 // 在一个复杂的方法中惊调用转账方法是不被鼓励的,因为可能遇到可重入个攻击或者拒绝服务攻击. // 我们明确的通过移除拍卖来防止充入攻击,卖价用 DOS 操作只能攻击他自己的资产 // 如果真有意外发生,可以通过调用取消拍卖 seller.transfer(sellerProceeds); } // 计算超出的额度 uint256 bidExcess = _bidAmount - price; // 返还超出的费用 msg.sender.transfer(bidExcess); // 触发拍卖成功事件 AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// 删除拍卖 内部函数 function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// 判断拍卖是否为激活状态 内部函数 只读 function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// 计算当前价格 内部函数 只读 /// 需要 2 个函数 /// 当前函数 计算事件 另一个 计算价格 function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // 确保正值 if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// 计算拍卖的当前价格 内部函数 纯计算 function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // 没有是有 SafeMath 或类似的函数,是因为所有公开方法 时间最大值是 64 位 货币最大只是 128 位 if (_secondsPassed >= _duration) { // 超出时间就是最后的价格 return _endingPrice; } else { // 线性插值?? 讲真我觉得不算拍卖,明明是插值价格 int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = (totalPriceChange * int256(_secondsPassed)) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// 收取拍卖费用 内部函数 只读 function _computeCut(uint256 _price) internal view returns (uint256) { return (_price * ownerCut) / 10000; } } /// 可停止的合约 contract Pausable is Ownable { event Pause(); // 停止事件 event Unpause(); // 继续事件 bool public paused = false; // what? 不是已经有一个 paused 了吗?? 上面的是管理层控制的中止 这个是所有者控制的中止 合约很多 modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// 定时拍卖 contract ClockAuction is Pausable, ClockAuctionBase { /// ERC721 接口的方法常量 ERC165 接口返回 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// 构造器函数 传入 nft 合约地址和手续费率 function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// 提出余额 外部方法 function withdrawBalance() external { address nftAddress = address(nonFungibleContract); // 要求是所有者或 nft 合约 require(msg.sender == owner || msg.sender == nftAddress); // 使用 send 确保就算转账失败也能继续运行 bool res = nftAddress.send(this.balance); } /// 创建一个新的拍卖 外部方法 仅限非停止状态 function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); // 检查开始价格 require(_endingPrice == uint256(uint128(_endingPrice))); // 检查结束价格 require(_duration == uint256(uint64(_duration))); // 检查拍卖持续时间 require(_owns(msg.sender, _tokenId)); // 检查所有者权限 _escrow(msg.sender, _tokenId); // 托管猫咪给合约 Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); // 保存拍卖信息 } /// 购买一个拍卖 完成拍卖和转移所有权 外部函数 可支付 仅限非停止状态 function bid(uint256 _tokenId) external payable whenNotPaused { _bid(_tokenId, msg.value); // 入股购买资金转移失败,会报异常 _transfer(msg.sender, _tokenId); } /// 取消没有胜者的拍卖 外部函数 /// 注意这个方法可以再合约被停止的情况下调用 function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息 require(_isOnAuction(auction)); // 检查拍卖是否激活状态 讲真的,从某种设计的角度来说,我觉得这种检查放到拍卖合约里面检查比较好,额,当前合约就是拍卖合约。。。 address seller = auction.seller; // 卖家地址 require(msg.sender == seller); // 检查调用者是不是卖家地址 _cancelAuction(_tokenId, seller); // 取消拍卖 } /// 取消拍卖 外部函数 仅限停止状态 仅限合约拥有者调用 /// 紧急情况下使用的方法 function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息 require(_isOnAuction(auction)); // 检查是否激活状态 _cancelAuction(_tokenId, auction.seller); // 取消拍卖 } /// 返回拍卖信息 外部函数 只读 function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息 require(_isOnAuction(auction)); // 检查拍卖是激活状态 return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// 获取拍卖当前价格 外部函数 只读 function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息 require(_isOnAuction(auction)); // 检查拍卖是激活状态 return _currentPrice(auction); // 计算当前价格 } } /// 繁育拍卖合约 contract SiringClockAuction is ClockAuction { // 在setSiringAuctionAddress方法调用中,合约检查确保我们在操作正确的拍卖 bool public isSiringClockAuction = true; // 委托父合约构造函数 function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// 创建一个拍卖 外部函数 /// 包装函数 要求调用方必须是 KittyCore 核心 function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); // 检查开始价格 require(_endingPrice == uint256(uint128(_endingPrice))); // 检查结束价格 require(_duration == uint256(uint64(_duration))); // 检查拍卖持续时间 require(msg.sender == address(nonFungibleContract)); // 要求调用者是 nft 合约地址 _escrow(_seller, _tokenId); // 授权拍卖 Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); // 添加拍卖信息 } /// 发起一个出价 外部函数 可支付 /// 要求调用方是 KittyCore 合约 因为所有的出价方法都被包装 /// 同样退回猫咪给卖家 看不懂说的啥 Also returns the kitty to the seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; _bid(_tokenId, msg.value); _transfer(seller, _tokenId); } } /// 销售拍卖合约 contract SaleClockAuction is ClockAuction { // 在setSaleAuctionAddress方法调用中,合约检查确保我们在操作正确的拍卖 bool public isSaleClockAuction = true; uint256 public gen0SaleCount; // 第 0 代猫咪售出计数 uint256[5] public lastGen0SalePrices; // 记录最近 5 只第 0 代卖出价格 // 委托父合约构造函数 function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// 创建新的拍卖 function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// 如果卖家是 NFT合约 更新价格 function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } /// 平均第 0 代售价 外部函数 只读 function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// 猫咪拍卖合约 创建销售和繁育的拍卖 /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract KittyAuction is KittyBreeding { // 当前拍卖合约变量定义在 KittyBase 中,KittyOwnership中有对变量的检查 // 销售拍卖参考第 0 代拍卖和 p2p 销售 // 繁育拍卖参考猫咪的繁育权拍卖 /// 设置销售拍卖合约 外部函数 仅限 CEO 调用 function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } /// 设置繁育排满合约 外部函数 仅限 CEO 调用 function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// 将一只猫咪放入销售拍卖 外部函数 仅限非停止状态调用 function createSaleAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // 拍卖合约检查输入参数大小 // 如果猫咪已经在拍卖中了,会报异常,因为所有权在拍卖合约那里 require(_owns(msg.sender, _kittyId)); // 确保猫咪不在怀孕状态 防止买到猫咪的人收到小猫咪的所有权 require(!isPregnant(_kittyId)); _approve(_kittyId, saleAuction); // 授权猫咪所有权给拍卖合约 // 如果参数有误拍卖合约会报异常。 调用成功会清除转移和繁育授权 saleAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// 将一只猫咪放入繁育拍卖 外部函数 仅限非停止状态调用 function createSiringAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // 拍卖合约检查输入参数大小 // 如果猫咪已经在拍卖中了,会报异常,因为所有权在拍卖合约那里 require(_owns(msg.sender, _kittyId)); require(isReadyToBreed(_kittyId)); // 检查猫咪是否在哺育状态 _approve(_kittyId, siringAuction); // 授权猫咪所有权给拍卖合约 // 如果参数有误拍卖合约会报异常。 调用成功会清除转移和繁育授权 siringAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// 出价完成一个繁育合约 猫咪会立即进入哺育状态 外部函数 可以支付 仅当非停止状态 function bidOnSiringAuction(uint256 _sireId, uint256 _matronId) external payable whenNotPaused { // 拍卖合约检查输入大小 require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // 计算当前价格 uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // 出价要高于当前价格和自动出生费用 // 如果出价失败,繁育合约会报异常 siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// 转移拍卖合约的余额到 KittyCore 外部函数仅限管理层调用 function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } /// 所有关系到创建猫咪的函数 contract KittyMinting is KittyAuction { // 限制合约创建猫咪的数量 uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // 第 0 代猫咪拍卖的常数 uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // 合约创建猫咪计数 uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// 创建推广猫咪 外部函数 仅限 COO 调用 function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { address kittyOwner = _owner; if (kittyOwner == address(0)) { kittyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createKitty(0, 0, 0, _genes, kittyOwner); } /// 创建第 0 代猫咪 外部函数 仅限 COO 调用 /// 为猫咪创建一个拍卖 function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); _approve(kittyId, saleAuction); saleAuction.createAuction( kittyId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } /// 计算第 0 代拍卖的价格 最后 5 个价格平均值 + 50% 内部函数 只读 function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// 加密猫核心 收集 哺育 领养? contract KittyCore is KittyMinting { // 这是加密猫的主要合约。为了让代码和逻辑部分分开,我们采用了 2 种方式。 // 第一,我们分开了部分兄弟合约管理拍卖和我们最高秘密的基因混合算法。 // 拍卖分开因为逻辑在某些方面比较复杂,另外也总是存在小 bug 的风险。 // 让这些风险在它们自己的合约里,我们可以升级它们,同时不用干扰记录着猫咪所有权的主合约。 // 基因混合算法分离是因为我们可以开源其他部分的算法,同时防止别人很容易就分叉弄明白基因部分是如何工作的。不用担心,我确定很快就会有人对齐逆向工程。 // 第二,我们分开核心合约产生多个文件是为了使用继承。这让我们保持关联的代码紧紧绑在一起,也避免了所有的东西都在一个巨型文件里。 // 分解如下: // // - KittyBase: 这是我们定义大多数基础代码的地方,这些代码贯穿了核心功能。包括主要数据存储,常量和数据类型,还有管理这些的内部函数。 // // - KittyAccessControl: 这个合约管理多种地址和限制特殊角色操作,像是 CEO CFO COO // // - KittyOwnership: 这个合约提供了基本的 NFT token 交易 请看 ERC721 // // - KittyBreeding: 这个包含了必要的哺育猫咪相关的方法,包括保证对公猫提供者的记录和对外部基因混合合约的依赖 // // - KittyAuctions: 这里我们有许多拍卖、出价和繁育的方法,实际的拍卖功能存储在 2 个兄弟合约(一个管销售 一个管繁育),拍卖创建和出价都要通过这个合约操作。 // // - KittyMinting: 这是包含创建第 0 代猫咪的最终门面合约。我们会制作 5000 个推广猫咪,这样的猫咪可以被分出去,比如当社区建立时。 // 所有的其他猫咪仅仅能够通过创建并立即进入拍卖,价格通过算法计算的方式分发出去。不要关心猫咪是如何被创建的,有一个 5 万的硬性限制。之后的猫咪都只能通过繁育生产。 // 当核心合约被破坏并且有必要升级时,设置这个变量 address public newContractAddress; /// 构造函数 创建主要的加密猫的合约实例 function KittyCore() public { paused = true; // 开始是暂停状态 ceoAddress = msg.sender; // 设置 ceo 地址 cooAddress = msg.sender; // 设置 coo 地址 // 创建神秘之猫,这个猫咪会产生第 0 代猫咪 _createKitty(0, 0, 0, uint256(-1), address(0)); } ///用于标记智能合约升级 防止出现严重 bug,这个方法只是记录新合约地址并触发合约升级事件。在这种情况下,客户端要采用新的合约地址。若升级发生,本合约会处于停止状态。 function setNewAddress(address _v2Address) external onlyCEO whenPaused { // 看 README.md 了解升级计划 newContractAddress = _v2Address; ContractUpgrade(_v2Address); // 触发合约升级事件 } /// fallback 函数 退回所有发送到本合约的以太币 除非是销售拍卖合约和繁育拍卖合约发来的 function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// 获取猫咪信息 function getKitty(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Kitty storage kit = kitties[_id]; isGestating = (kit.siringWithId != 0); // 如果 siringWithId 不是 0 表明处于妊娠状态 isReady = (kit.cooldownEndBlock <= block.number); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndBlock); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } /// 启动合约 要求所有的外部合约地址都被设置,才能够启动合约。如果升级合约被设置了,那么无法启动合约 公开函数 要求 CEO 才能调用 仅限合约停止状态调用 /// public 我们才能调用父合约的外部方法 function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // 提现方法 外部 仅限 CFO function withdrawBalance() external onlyCFO { uint256 balance = this.balance; // 减去所有怀孕的猫咪数量+1作为余量 uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.send(balance - subtractFees); } } }
是否猫咪怀孕了 公开 只读 如果 siringWithId 被设置了表明就是怀孕了
function isPregnant(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); return kitties[_kittyId].siringWithId != 0; }
967,894
pragma solidity ^0.4.16; contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract tokenRecipient { event receivedEther(address sender, uint amount); event receivedTokens(address _from, uint256 _value, address _token, bytes _extraData); function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData){ Token t = Token(_token); require(t.transferFrom(_from, this, _value)); receivedTokens(_from, _value, _token, _extraData); } function () payable { receivedEther(msg.sender, msg.value); } } interface Token { function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } contract TimeLockMultisig is owned, tokenRecipient { Proposal[] public proposals; uint public numProposals; mapping (address => uint) public memberId; Member[] public members; uint minimumTime = 10; event ProposalAdded(uint proposalID, address recipient, uint amount, string description); event Voted(uint proposalID, bool position, address voter, string justification); event ProposalExecuted(uint proposalID, int result, uint deadline); event MembershipChanged(address member, bool isMember); struct Proposal { address recipient; uint amount; string description; bool executed; int currentResult; bytes32 proposalHash; uint creationDate; Vote[] votes; mapping (address => bool) voted; } struct Member { address member; string name; uint memberSince; } struct Vote { bool inSupport; address voter; string justification; } // Modifier that allows only shareholders to vote and create new proposals modifier onlyMembers { require(memberId[msg.sender] != 0); _; } /** * Constructor function * * First time setup */ function TimeLockMultisig(address founder, address[] initialMembers, uint minimumAmountOfMinutes) payable { if (founder != 0) owner = founder; if (minimumAmountOfMinutes !=0) minimumTime = minimumAmountOfMinutes; // It’s necessary to add an empty first member addMember(0, ''); // and let's add the founder, to save a step later addMember(owner, 'founder'); changeMembers(initialMembers, true); } /** * Add member * * @param targetMember address to add as a member * @param memberName label to give this member address */ function addMember(address targetMember, string memberName) onlyOwner { uint id; if (memberId[targetMember] == 0) { memberId[targetMember] = members.length; id = members.length++; } else { id = memberId[targetMember]; } members[id] = Member({member: targetMember, memberSince: now, name: memberName}); MembershipChanged(targetMember, true); } /** * Remove member * * @param targetMember the member to remove */ function removeMember(address targetMember) onlyOwner { require(memberId[targetMember] != 0); for (uint i = memberId[targetMember]; i<members.length-1; i++){ members[i] = members[i+1]; } delete members[members.length-1]; members.length--; } /** * Edit existing members * * @param newMembers array of addresses to update * @param canVote new voting value that all the values should be set to */ function changeMembers(address[] newMembers, bool canVote) { for (uint i = 0; i < newMembers.length; i++) { if (canVote) addMember(newMembers[i], ''); else removeMember(newMembers[i]); } } /** * Add Proposal * * Propose to send `weiAmount / 1e18` ether to `beneficiary` for `jobDescription`. `transactionBytecode ? Contains : Does not contain` code. * * @param beneficiary who to send the ether to * @param weiAmount amount of ether to send, in wei * @param jobDescription Description of job * @param transactionBytecode bytecode of transaction */ function newProposal( address beneficiary, uint weiAmount, string jobDescription, bytes transactionBytecode ) onlyMembers returns (uint proposalID) { proposalID = proposals.length++; Proposal storage p = proposals[proposalID]; p.recipient = beneficiary; p.amount = weiAmount; p.description = jobDescription; p.proposalHash = sha3(beneficiary, weiAmount, transactionBytecode); p.executed = false; p.creationDate = now; ProposalAdded(proposalID, beneficiary, weiAmount, jobDescription); numProposals = proposalID+1; vote(proposalID, true, ''); return proposalID; } /** * Add proposal in Ether * * Propose to send `etherAmount` ether to `beneficiary` for `jobDescription`. `transactionBytecode ? Contains : Does not contain` code. * This is a convenience function to use if the amount to be given is in round number of ether units. * * @param beneficiary who to send the ether to * @param etherAmount amount of ether to send * @param jobDescription Description of job * @param transactionBytecode bytecode of transaction */ function newProposalInEther( address beneficiary, uint etherAmount, string jobDescription, bytes transactionBytecode ) onlyMembers returns (uint proposalID) { return newProposal(beneficiary, etherAmount * 1 ether, jobDescription, transactionBytecode); } /** * Check if a proposal code matches * * @param proposalNumber ID number of the proposal to query * @param beneficiary who to send the ether to * @param weiAmount amount of ether to send * @param transactionBytecode bytecode of transaction */ function checkProposalCode( uint proposalNumber, address beneficiary, uint weiAmount, bytes transactionBytecode ) constant returns (bool codeChecksOut) { Proposal storage p = proposals[proposalNumber]; return p.proposalHash == sha3(beneficiary, weiAmount, transactionBytecode); } /** * Log a vote for a proposal * * Vote `supportsProposal? in support of : against` proposal #`proposalNumber` * * @param proposalNumber number of proposal * @param supportsProposal either in favor or against it * @param justificationText optional justification text */ function vote( uint proposalNumber, bool supportsProposal, string justificationText ) onlyMembers { Proposal storage p = proposals[proposalNumber]; // Get the proposal require(p.voted[msg.sender] != true); // If has already voted, cancel p.voted[msg.sender] = true; // Set this voter as having voted if (supportsProposal) { // If they support the proposal p.currentResult++; // Increase score } else { // If they don't p.currentResult--; // Decrease the score } // Create a log of this event Voted(proposalNumber, supportsProposal, msg.sender, justificationText); // If you can execute it now, do it if ( now > proposalDeadline(proposalNumber) && p.currentResult > 0 && p.proposalHash == sha3(p.recipient, p.amount, '') && supportsProposal) { executeProposal(proposalNumber, ''); } } function proposalDeadline(uint proposalNumber) constant returns(uint deadline) { Proposal storage p = proposals[proposalNumber]; uint factor = calculateFactor(uint(p.currentResult), (members.length - 1)); return p.creationDate + uint(factor * minimumTime * 1 minutes); } function calculateFactor(uint a, uint b) constant returns (uint factor) { return 2**(20 - (20 * a)/b); } /** * Finish vote * * Count the votes proposal #`proposalNumber` and execute it if approved * * @param proposalNumber proposal number * @param transactionBytecode optional: if the transaction contained a bytecode, you need to send it */ function executeProposal(uint proposalNumber, bytes transactionBytecode) { Proposal storage p = proposals[proposalNumber]; require(now >= proposalDeadline(proposalNumber) // If it is past the voting deadline && p.currentResult > 0 // and a minimum quorum has been reached && !p.executed // and it is not currently being executed && checkProposalCode(proposalNumber, p.recipient, p.amount, transactionBytecode)); // and the supplied code matches the proposal... p.executed = true; assert(p.recipient.call.value(p.amount)(transactionBytecode)); // Fire Events ProposalExecuted(proposalNumber, p.currentResult, proposalDeadline(proposalNumber)); } }
Constructor function First time setup/ It’s necessary to add an empty first member and let's add the founder, to save a step later
function TimeLockMultisig(address founder, address[] initialMembers, uint minimumAmountOfMinutes) payable { if (founder != 0) owner = founder; if (minimumAmountOfMinutes !=0) minimumTime = minimumAmountOfMinutes; addMember(0, ''); addMember(owner, 'founder'); changeMembers(initialMembers, true); }
12,905,190
./full_match/80001/0xf223384aD66483652974B35937A29C5586F4c375/sources/contracts/ERC20InvictusFund.sol
Sets exit fee percentage for redemptions. newExitFeePercentage The percentage of the redemption amount for exit fees./
function setExitFeePercentage(uint24 newExitFeePercentage) external onlyOwner { require(newExitFeePercentage > 0, "Invalid percentage"); require(newExitFeePercentage < 3000, "Percentage too high"); exitFeePercentage = newExitFeePercentage; emit UpdateExitFeePercentage(newExitFeePercentage); }
864,443
./full_match/43113/0x0A877260Fd2DbA21640DAC1F106ec64484FAC81B/sources/contracts/3_Ballot.sol
Convert an amount of the output token to an equivalent amount of input token_. - Sufficient balance check is covered in the `_burn` function so avoid having the explicit check here. - No need for the reentrancy check as the state already updated before the transfer of funds. - Implementation doesn't assume that decimals of the swap tokens and wrapper token is same so implementation inherently converts the `amount_` to the required precision. `amount_` always follow the precision of the swap tokens not the wrapper tokens. token_ address of token to receive amount_ amount of token to swap/receive/
function unswap(address token_, uint256 amount_) external { _isValidSwapToken(token_); require(IERC20(token_).balanceOf(address(this)) >= amount_, "Wrapper: Insufficient swap token funds"); uint256 fromAmt = _toDenominatedDecimals(token_, address(this), amount_); _burn(msg.sender, fromAmt); IERC20(token_).safeTransfer(msg.sender, amount_); emit Unswapped(address(this), token_, fromAmt, amount_); }
7,167,513
./partial_match/42/0xce0454371c7e1c1a6c3408E01F7e2CdCd9591c2f/sources/YieldMasterFarm.sol
View function to see pending YieldMaster on frontend.
function pendingYieldMaster(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accYieldMasterPerShare = pool.accYieldMasterPerShare; uint256 sharesTotal = IStrategy(pool.strat).sharesTotal(); if (block.number > pool.lastRewardBlock && sharesTotal != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 YieldMasterReward = multiplier.mul(YieldMasterPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accYieldMasterPerShare = accYieldMasterPerShare.add( YieldMasterReward.mul(1e12).div(sharesTotal) ); } return user.shares.mul(accYieldMasterPerShare).div(1e12).sub(user.rewardDebt); }
3,375,577
./full_match/8453/0x7870837ffe670E62d4e601393D454f1b8649F7f9/sources/src/token/ERC20/governance/GovernanceWrappedERC20.sol
@inheritdoc ERC20VotesUpgradeable
function _mint( address to, uint256 amount ) internal override(ERC20VotesUpgradeable, ERC20Upgradeable) { super._mint(to, amount); }
11,543,947
// SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "../openzeppelin/access/AccessControl.sol"; import "../openzeppelin/utils/math/SafeMath.sol"; import "../openzeppelin/token/ERC20/SafeERC20.sol"; import "../openzeppelin/token/ERC20/IERC20.sol"; import "../sablierhq/Sablier.sol"; import "./ITokenVesting.sol"; /** * @title TokenVesting contract for linearly vesting tokens to the respective vesting beneficiary * @dev This contract receives accepted proposals from the Manager contract, and pass it to sablier contract * @dev all the tokens to be vested by the vesting beneficiary. It releases these tokens when called * @dev upon in a continuous-like linear fashion. * @notice This contract use https://github.com/sablierhq/sablier-smooth-contracts/blob/master/contracts/Sablier.sol */ contract TokenVesting is ITokenVesting, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; address sablier; uint256 constant CREATOR_IX = 0; uint256 constant ROLL_IX = 1; uint256 constant REFERRAL_IX = 2; uint256 public constant DAYS_IN_SECONDS = 24 * 60 * 60; mapping(address => VestingInfo) public vestingInfo; mapping(address => mapping(uint256 => Beneficiary)) public beneficiaries; mapping(address => address[]) public beneficiaryTokens; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Ownable: caller is not the owner" ); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); grantRole(DEFAULT_ADMIN_ROLE, newOwner); revokeRole(DEFAULT_ADMIN_ROLE, msg.sender); } constructor(address newOwner) { _setupRole(DEFAULT_ADMIN_ROLE, newOwner); } function setSablier(address _sablier) external onlyOwner { sablier = _sablier; } /** * @dev Method to add a token into TokenVesting * @param _token address Address of token * @param _beneficiaries address[3] memory Address of vesting beneficiary * @param _proportions uint256[3] memory Proportions of vesting beneficiary * @param _vestingPeriodInDays uint256 Period of vesting, in units of Days, to be converted * @notice This emits an Event LogTokenAdded which is indexed by the token address */ function addToken( address _token, address[3] calldata _beneficiaries, uint256[3] calldata _proportions, uint256 _vestingPeriodInDays ) external override onlyOwner { uint256 duration = uint256(_vestingPeriodInDays).mul(DAYS_IN_SECONDS); require(duration > 0, "VESTING: period can't be zero"); uint256 stopTime = block.timestamp.add(duration); uint256 initial = IERC20(_token).balanceOf(address(this)); vestingInfo[_token] = VestingInfo({ vestingBeneficiary: _beneficiaries[0], totalBalance: initial, beneficiariesCount: 3, // this is to create a struct compatible with any number but for now is always 3 start: block.timestamp, stop: stopTime }); IERC20(_token).approve(sablier, 2**256 - 1); IERC20(_token).approve(address(this), 2**256 - 1); for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (_beneficiaries[i] == address(0)) { continue; } beneficiaries[_token][i].beneficiary = _beneficiaries[i]; beneficiaries[_token][i].proportion = _proportions[i]; uint256 deposit = _proportions[i]; if (deposit == 0) { continue; } // we store the remaing to guarantee deposit be multiple of period. We send that remining at the end of period. uint256 remaining = deposit % duration; uint256 streamId = Sablier(sablier).createStream( _beneficiaries[i], deposit.sub(remaining), _token, block.timestamp, stopTime ); beneficiaries[_token][i].streamId = streamId; beneficiaries[_token][i].remaining = remaining; beneficiaryTokens[_beneficiaries[i]].push(_token); } emit LogTokenAdded(_token, _beneficiaries[0], _vestingPeriodInDays); } function getBeneficiaryId(address _token, address _beneficiary) internal view returns (uint256) { for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (beneficiaries[_token][i].beneficiary == _beneficiary) { return i; } } revert("VESTING: invalid vesting address"); } function release(address _token, address _beneficiary) external override { uint256 ix = getBeneficiaryId(_token, _beneficiary); uint256 streamId = beneficiaries[_token][ix].streamId; if (!Sablier(sablier).isEntity(streamId)) { return; } uint256 balance = Sablier(sablier).balanceOf(streamId, _beneficiary); bool withdrawResult = Sablier(sablier).withdrawFromStream(streamId, balance); require(withdrawResult, "VESTING: Error calling withdrawFromStream"); // if vesting duration already finish then release the final dust if ( vestingInfo[_token].stop < block.timestamp && beneficiaries[_token][ix].remaining > 0 ) { IERC20(_token).safeTransferFrom( address(this), _beneficiary, beneficiaries[_token][ix].remaining ); } } function releaseableAmount(address _token) public view override returns (uint256) { uint256 total = 0; for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (Sablier(sablier).isEntity(beneficiaries[_token][i].streamId)) { total = total + Sablier(sablier).balanceOf( beneficiaries[_token][i].streamId, beneficiaries[_token][i].beneficiary ); } } return total; } function releaseableAmountByAddress(address _token, address _beneficiary) public view override returns (uint256) { uint256 ix = getBeneficiaryId(_token, _beneficiary); uint256 streamId = beneficiaries[_token][ix].streamId; return Sablier(sablier).balanceOf(streamId, _beneficiary); } function vestedAmount(address _token) public view override returns (uint256) { VestingInfo memory info = vestingInfo[_token]; if (block.timestamp >= info.stop) { return info.totalBalance; } else { uint256 duration = info.stop.sub(info.start); return info.totalBalance.mul(block.timestamp.sub(info.start)).div( duration ); } } function getVestingInfo(address _token) external view override returns (VestingInfo memory) { return vestingInfo[_token]; } function updateVestingAddress( address _token, uint256 ix, address _vestingBeneficiary ) internal { if ( vestingInfo[_token].vestingBeneficiary == beneficiaries[_token][ix].beneficiary ) { vestingInfo[_token].vestingBeneficiary = _vestingBeneficiary; } beneficiaries[_token][ix].beneficiary = _vestingBeneficiary; uint256 deposit = 0; uint256 remaining = 0; { uint256 streamId = beneficiaries[_token][ix].streamId; // if there's no pending this will revert and it's ok because has no sense to update the address uint256 pending = Sablier(sablier).balanceOf(streamId, address(this)); uint256 duration = vestingInfo[_token].stop.sub(block.timestamp); deposit = pending.add(beneficiaries[_token][ix].remaining); remaining = deposit % duration; bool cancelResult = Sablier(sablier).cancelStream( beneficiaries[_token][ix].streamId ); require(cancelResult, "VESTING: Error calling cancelStream"); } uint256 streamId = Sablier(sablier).createStream( _vestingBeneficiary, deposit.sub(remaining), _token, block.timestamp, vestingInfo[_token].stop ); beneficiaries[_token][ix].streamId = streamId; beneficiaries[_token][ix].remaining = remaining; emit LogBeneficiaryUpdated(_token, _vestingBeneficiary); } function setVestingAddress( address _vestingBeneficiary, address _token, address _newVestingBeneficiary ) external override onlyOwner { uint256 ix = getBeneficiaryId(_token, _vestingBeneficiary); updateVestingAddress(_token, ix, _newVestingBeneficiary); } function setVestingReferral( address _vestingBeneficiary, address _token, address _vestingReferral ) external override onlyOwner { require( _vestingBeneficiary == vestingInfo[_token].vestingBeneficiary, "VESTING: Only creator" ); updateVestingAddress(_token, REFERRAL_IX, _vestingReferral); } function getAllTokensByBeneficiary(address _beneficiary) public view override returns (address[] memory) { return beneficiaryTokens[_beneficiary]; } function releaseAll(address _beneficiary) public override { address[] memory array = beneficiaryTokens[_beneficiary]; for (uint256 i = 0; i < array.length; i++) { this.release(array[i], _beneficiary); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../utils/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.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity =0.7.6; import "../openzeppelin/utils/Pausable.sol"; import "../openzeppelin/access/Ownable.sol"; import "../openzeppelin/token/ERC20/IERC20.sol"; import "../openzeppelin/utils/ReentrancyGuard.sol"; import "./compound/Exponential.sol"; import "./interfaces/IERC1620.sol"; import "./Types.sol"; /** * @title Sablier's Money Streaming * @author Sablier */ contract Sablier is IERC1620, Exponential, ReentrancyGuard { /*** Storage Properties ***/ /** * @dev The amount of interest has been accrued per token address. */ mapping(address => uint256) private earnings; /** * @notice The percentage fee charged by the contract on the accrued interest. */ Exp public fee; /** * @notice Counter for new stream ids. */ uint256 public nextStreamId; /** * @dev The stream objects identifiable by their unsigned integer ids. */ mapping(uint256 => Types.Stream) private streams; /*** Modifiers ***/ /** * @dev Throws if the caller is not the sender of the recipient of the stream. */ modifier onlySenderOrRecipient(uint256 streamId) { require( msg.sender == streams[streamId].sender || msg.sender == streams[streamId].recipient, "caller is not the sender or the recipient of the stream" ); _; } /** * @dev Throws if the provided id does not point to a valid stream. */ modifier streamExists(uint256 streamId) { require(streams[streamId].isEntity, "stream does not exist"); _; } /*** Contract Logic Starts Here */ constructor() public { nextStreamId = 1; } /*** View Functions ***/ function isEntity(uint256 streamId) external view returns (bool) { return streams[streamId].isEntity; } /** * @dev Returns the compounding stream with all its properties. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream to query. * @dev The stream object. */ function getStream(uint256 streamId) external view override streamExists(streamId) returns ( address sender, address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond ) { sender = streams[streamId].sender; recipient = streams[streamId].recipient; deposit = streams[streamId].deposit; tokenAddress = streams[streamId].tokenAddress; startTime = streams[streamId].startTime; stopTime = streams[streamId].stopTime; remainingBalance = streams[streamId].remainingBalance; ratePerSecond = streams[streamId].ratePerSecond; } /** * @dev Returns either the delta in seconds between `block.timestamp` and `startTime` or * between `stopTime` and `startTime, whichever is smaller. If `block.timestamp` is before * `startTime`, it returns 0. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream for which to query the delta. * @dev The time delta in seconds. */ function deltaOf(uint256 streamId) public view streamExists(streamId) returns (uint256 delta) { Types.Stream memory stream = streams[streamId]; if (block.timestamp <= stream.startTime) return 0; if (block.timestamp < stream.stopTime) return block.timestamp - stream.startTime; return stream.stopTime - stream.startTime; } struct BalanceOfLocalVars { MathError mathErr; uint256 recipientBalance; uint256 withdrawalAmount; uint256 senderBalance; } /** * @dev Returns the available funds for the given stream id and address. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream for which to query the balance. * @param who The address for which to query the balance. * @dev @balance uint256 The total funds allocated to `who` as uint256. */ function balanceOf(uint256 streamId, address who) public view override streamExists(streamId) returns (uint256 balance) { Types.Stream memory stream = streams[streamId]; BalanceOfLocalVars memory vars; uint256 delta = deltaOf(streamId); (vars.mathErr, vars.recipientBalance) = mulUInt( delta, stream.ratePerSecond ); require( vars.mathErr == MathError.NO_ERROR, "recipient balance calculation error" ); /* * If the stream `balance` does not equal `deposit`, it means there have been withdrawals. * We have to subtract the total amount withdrawn from the amount of money that has been * streamed until now. */ if (stream.deposit > stream.remainingBalance) { (vars.mathErr, vars.withdrawalAmount) = subUInt( stream.deposit, stream.remainingBalance ); assert(vars.mathErr == MathError.NO_ERROR); (vars.mathErr, vars.recipientBalance) = subUInt( vars.recipientBalance, vars.withdrawalAmount ); /* `withdrawalAmount` cannot and should not be bigger than `recipientBalance`. */ assert(vars.mathErr == MathError.NO_ERROR); } if (who == stream.recipient) return vars.recipientBalance; if (who == stream.sender) { (vars.mathErr, vars.senderBalance) = subUInt( stream.remainingBalance, vars.recipientBalance ); /* `recipientBalance` cannot and should not be bigger than `remainingBalance`. */ assert(vars.mathErr == MathError.NO_ERROR); return vars.senderBalance; } return 0; } /*** Public Effects & Interactions Functions ***/ struct CreateStreamLocalVars { MathError mathErr; uint256 duration; uint256 ratePerSecond; } /** * @notice Creates a new stream funded by `msg.sender` and paid towards `recipient`. * @dev Throws if paused. * Throws if the recipient is the zero address, the contract itself or the caller. * Throws if the deposit is 0. * Throws if the start time is before `block.timestamp`. * Throws if the stop time is before the start time. * Throws if the duration calculation has a math error. * Throws if the deposit is smaller than the duration. * Throws if the deposit is not a multiple of the duration. * Throws if the rate calculation has a math error. * Throws if the next stream id calculation has a math error. * Throws if the contract is not allowed to transfer enough tokens. * Throws if there is a token transfer failure. * @param recipient The address towards which the money is streamed. * @param deposit The amount of money to be streamed. * @param tokenAddress The ERC20 token to use as streaming currency. * @param startTime The unix timestamp for when the stream starts. * @param stopTime The unix timestamp for when the stream stops. * @return The uint256 id of the newly created stream. */ function createStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ) public override returns (uint256) { require(recipient != address(0x00), "stream to the zero address"); require(recipient != address(this), "stream to the contract itself"); require(recipient != msg.sender, "stream to the caller"); require(deposit > 0, "deposit is zero"); require( startTime >= block.timestamp, "start time before block.timestamp" ); require(stopTime > startTime, "stop time before the start time"); CreateStreamLocalVars memory vars; (vars.mathErr, vars.duration) = subUInt(stopTime, startTime); /* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know `stopTime` is higher than `startTime`. */ assert(vars.mathErr == MathError.NO_ERROR); /* Without this, the rate per second would be zero. */ require(deposit >= vars.duration, "deposit smaller than time delta"); require( deposit % vars.duration == 0, "deposit not multiple of time delta" ); (vars.mathErr, vars.ratePerSecond) = divUInt(deposit, vars.duration); /* `divUInt` can only return MathError.DIVISION_BY_ZERO but we know `duration` is not zero. */ assert(vars.mathErr == MathError.NO_ERROR); /* Create and store the stream object. */ uint256 streamId = nextStreamId; streams[streamId] = Types.Stream({ remainingBalance: deposit, deposit: deposit, isEntity: true, ratePerSecond: vars.ratePerSecond, recipient: recipient, sender: msg.sender, startTime: startTime, stopTime: stopTime, tokenAddress: tokenAddress }); /* Increment the next stream id. */ (vars.mathErr, nextStreamId) = addUInt(nextStreamId, uint256(1)); require( vars.mathErr == MathError.NO_ERROR, "next stream id calculation error" ); require( IERC20(tokenAddress).transferFrom( msg.sender, address(this), deposit ), "token transfer failure" ); emit CreateStream( streamId, msg.sender, recipient, deposit, tokenAddress, startTime, stopTime ); return streamId; } struct WithdrawFromStreamLocalVars { MathError mathErr; } /** * @notice Withdraws from the contract to the recipient's account. * @dev Throws if the id does not point to a valid stream. * Throws if the caller is not the sender or the recipient of the stream. * Throws if the amount exceeds the available balance. * Throws if there is a token transfer failure. * @param streamId The id of the stream to withdraw tokens from. * @param amount The amount of tokens to withdraw. * @return bool true=success, otherwise false. */ function withdrawFromStream(uint256 streamId, uint256 amount) external override nonReentrant streamExists(streamId) onlySenderOrRecipient(streamId) returns (bool) { require(amount > 0, "amount is zero"); Types.Stream memory stream = streams[streamId]; WithdrawFromStreamLocalVars memory vars; uint256 balance = balanceOf(streamId, stream.recipient); require(balance >= amount, "amount exceeds the available balance"); (vars.mathErr, streams[streamId].remainingBalance) = subUInt( stream.remainingBalance, amount ); /** * `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `remainingBalance` is at least * as big as `amount`. */ assert(vars.mathErr == MathError.NO_ERROR); if (streams[streamId].remainingBalance == 0) delete streams[streamId]; require( IERC20(stream.tokenAddress).transfer(stream.recipient, amount), "token transfer failure" ); emit WithdrawFromStream(streamId, stream.recipient, amount); return true; } /** * @notice Cancels the stream and transfers the tokens back on a pro rata basis. * @dev Throws if the id does not point to a valid stream. * Throws if the caller is not the sender or the recipient of the stream. * Throws if there is a token transfer failure. * @param streamId The id of the stream to cancel. * @return bool true=success, otherwise false. */ function cancelStream(uint256 streamId) external override nonReentrant streamExists(streamId) onlySenderOrRecipient(streamId) returns (bool) { Types.Stream memory stream = streams[streamId]; uint256 senderBalance = balanceOf(streamId, stream.sender); uint256 recipientBalance = balanceOf(streamId, stream.recipient); delete streams[streamId]; IERC20 token = IERC20(stream.tokenAddress); if (recipientBalance > 0) require( token.transfer(stream.recipient, recipientBalance), "recipient token transfer failure" ); if (senderBalance > 0) require( token.transfer(stream.sender, senderBalance), "sender token transfer failure" ); emit CancelStream( streamId, stream.sender, stream.recipient, senderBalance, recipientBalance ); return true; } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma experimental ABIEncoderV2; interface ITokenVesting { event Released( address indexed token, address vestingBeneficiary, uint256 amount ); event LogTokenAdded( address indexed token, address vestingBeneficiary, uint256 vestingPeriodInDays ); event LogBeneficiaryUpdated( address indexed token, address vestingBeneficiary ); struct VestingInfo { address vestingBeneficiary; uint256 totalBalance; uint256 beneficiariesCount; uint256 start; uint256 stop; } struct Beneficiary { address beneficiary; uint256 proportion; uint256 streamId; uint256 remaining; } function addToken( address _token, address[3] calldata _beneficiaries, uint256[3] calldata _proportions, uint256 _vestingPeriodInDays ) external; function release(address _token, address _beneficiary) external; function releaseableAmount(address _token) external view returns (uint256); function releaseableAmountByAddress(address _token, address _beneficiary) external view returns (uint256); function vestedAmount(address _token) external view returns (uint256); function getVestingInfo(address _token) external view returns (VestingInfo memory); function setVestingAddress( address _vestingBeneficiary, address _token, address _newVestingBeneficiary ) external; function setVestingReferral( address _vestingBeneficiary, address _token, address _vestingReferral ) external; function getAllTokensByBeneficiary(address _beneficiary) external view returns (address[] memory); function releaseAll(address _beneficiary) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: 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 "./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.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity =0.7.6; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-decision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: rational })); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: scaledMantissa })); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: descaledMantissa })); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({ mantissa: product })); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({ mantissa: a }), Exp({ mantissa: b })); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo. } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } pragma solidity =0.7.6; /** * @title ERC-1620 Money Streaming Standard * @author Sablier * @dev See https://eips.ethereum.org/EIPS/eip-1620 */ interface IERC1620 { /** * @notice Emits when a stream is successfully created. */ event CreateStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ); /** * @notice Emits when the recipient of a stream withdraws a portion or all their pro rata share of the stream. */ event WithdrawFromStream( uint256 indexed streamId, address indexed recipient, uint256 amount ); /** * @notice Emits when a stream is successfully cancelled and tokens are transferred back on a pro rata basis. */ event CancelStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 senderBalance, uint256 recipientBalance ); function balanceOf(uint256 streamId, address who) external view returns (uint256 balance); function getStream(uint256 streamId) external view returns ( address sender, address recipient, uint256 deposit, address token, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond ); function createStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ) external returns (uint256 streamId); function withdrawFromStream(uint256 streamId, uint256 funds) external returns (bool); function cancelStream(uint256 streamId) external returns (bool); } pragma solidity =0.7.6; /** * @title Sablier Types * @author Sablier */ library Types { struct Stream { uint256 deposit; uint256 ratePerSecond; uint256 remainingBalance; uint256 startTime; uint256 stopTime; address recipient; address sender; address tokenAddress; bool isEntity; } } pragma solidity =0.7.6; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }
Multiplies two exponentials, returning a new exponential./
function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { } addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); }
12,569,877
pragma solidity ^0.5.1; contract AdminInterface { function setCapacity( uint _capacity ) public returns(bool); function addCoinBase( address payable _coinBase ) public returns(bool); function initHolderAddr( address payable _coinBase, address payable _holderAddr ) public returns(bool); function calVoteResult() public returns(bool); } contract VoteInterface { /** * 投票 */ function vote( address payable voterAddr, address payable candidateAddr, uint num ) public returns(bool); /** * 用于批量投票 */ function batchVote( address payable voterAddr, address payable[] memory candidateAddrs, uint[] memory nums ) public returns(bool); function updateCoinBase( address payable _coinBase, address payable _newCoinBase ) public returns(bool); function setHolderAddr( address payable _coinBase, address payable _holderAddr ) public returns(bool); function updateCandidateAddr( address payable _candidateAddr, address payable _newCandidateAddr ) public returns(bool); /** * 撤回对某个候选人的投票 */ function cancelVoteForCandidate( address payable voterAddr, address payable candidateAddr, uint num ) public returns(bool); function refreshVoteForAll() public returns(bool); function refreshVoteForVoter(address payable voterAddr) public returns(bool); } contract FetchVoteInterface { /** * 是否为竞选阶段 */ function isRunUpStage() public view returns (bool); /** * 获取所有候选人的详细信息 */ function fetchAllCandidates() public view returns ( address payable[] memory ); /** * 获取所有投票人的详细信息 */ function fetchAllVoters() public view returns ( address payable[] memory, uint[] memory ); /** * 获取所有投票人的投票情况 */ function fetchVoteInfoForVoter( address payable voterAddr ) public view returns ( address payable[] memory, uint[] memory ); /** * 获取某个候选人的总得票数 */ function fetchVoteNumForCandidate( address payable candidateAddr ) public view returns (uint); /** * 获取某个投票人已投票数 */ function fetchVoteNumForVoter( address payable voterAddr ) public view returns (uint); /** * 获取某个候选人被投票详细情况 */ function fetchVoteInfoForCandidate( address payable candidateAddr ) public view returns ( address payable[] memory, uint[] memory ); function fetchVoteNumForVoterToCandidate( address payable voterAddr, address payable candidateAddr ) public view returns (uint); /** * 获取所有候选人的得票情况 */ function fetchAllVoteResult() public view returns ( address payable[] memory, uint[] memory ); function getHolderAddr( address payable _coinBase ) public view returns ( address payable ); function getAllCoinBases( ) public view returns ( address payable[] memory ); } contract HpbNodesInterface { function addStage() public returns(bool); function addHpbNodeBatch( address payable[] memory coinbases, bytes32[] memory cid1s, bytes32[] memory cid2s, bytes32[] memory hids ) public returns(bool); } contract ContractSimpleProxyInterface{ function addContractMethod( address _contractAddr, bytes4 _methodId ) public returns(bool); function updateInvokeContract( uint invokeIndex, uint contractIndex, uint methodIdIndex )public returns(bool); function getContractIndexAndMethodIndex( address _contractAddr, bytes4 _methodId )public view returns (uint,uint); function getInvokeContract( uint invokeIndex ) public view returns (address,bytes4); } contract Ownable { address payable public owner; modifier onlyOwner { require(msg.sender == owner); // Do not forget the "_;"! It will be replaced by the actual function // body when the modifier is used. _; } function transferOwnership(address payable newOwner) onlyOwner public returns(bool) { owner = newOwner; addAdmin(newOwner); deleteAdmin(owner); return true; } function getOwner() public view returns (address payable) { return owner; } // 合约管理员,可以添加和删除候选人 mapping (address => address payable) public adminMap; modifier onlyAdmin { require(adminMap[msg.sender] != address(0)); _; } function addAdmin(address payable addr) onlyOwner public returns(bool) { require(adminMap[addr] == address(0)); adminMap[addr] = addr; return true; } function deleteAdmin(address payable addr) onlyOwner public returns(bool) { require(adminMap[addr] != address(0)); adminMap[addr] = address(0); delete adminMap[addr]; return true; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div( uint256 a, uint256 b ) internal pure returns ( uint256 ) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub( uint256 a, uint256 b ) internal pure returns ( uint256 ) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add( uint256 a, uint256 b ) internal pure returns ( uint256 c ) { c = a + b; assert(c >= a); return c; } } contract NodeBallotProx is Ownable{ using SafeMath for uint256; address payable public hpbNodesAddress; address payable public contractSimpleProxyAddress; address payable[] public nodeBallotAddrs; mapping (address => uint) public nodeBallotIndex; address payable public nodeBallotAddrInService; function _getAdminInterface( uint _index ) internal view returns ( AdminInterface ) { require(_index != 0); return AdminInterface(nodeBallotAddrs[_index]); } function _getVoteInterface( uint _index ) internal view returns ( VoteInterface ) { require(_index != 0); return VoteInterface(nodeBallotAddrs[_index]); } function _getFetchVoteInterface( uint _index ) internal view returns ( FetchVoteInterface ) { require(_index != 0); return FetchVoteInterface(nodeBallotAddrs[_index]); } function _getHpbNodesInterface() internal view returns ( HpbNodesInterface ) { require(hpbNodesAddress != address(0)); return HpbNodesInterface(hpbNodesAddress); } function _getContractSimpleProxyInterface() internal view returns ( ContractSimpleProxyInterface ) { require(contractSimpleProxyAddress != address(0)); return ContractSimpleProxyInterface(contractSimpleProxyAddress); } function getLastestBallotAddrAndIndex() public view returns( address payable, uint ) { return ( nodeBallotAddrs[nodeBallotAddrs.length - 1], nodeBallotAddrs.length - 1 ); } function updateCandidateAddr( address payable _candidateAddr, address payable _newCandidateAddr ) public returns(bool) { return updateCandidateAddrByIndex(nodeBallotAddrs.length - 1, _candidateAddr, _newCandidateAddr); } function updateCandidateAddrByIndex( uint index, address payable _candidateAddr, address payable _newCandidateAddr )onlyAdmin public returns(bool) { return _getVoteInterface(index).updateCandidateAddr(_candidateAddr, _newCandidateAddr); } function batchUpdateCandidateAddr( address payable[] memory _candidateAddrs, address payable[] memory _newCandidateAddrs ) public returns(bool) { return batchUpdateCandidateAddrByIndex(nodeBallotAddrs.length - 1, _candidateAddrs,_newCandidateAddrs); } function batchUpdateCandidateAddrByIndex( uint index, address payable[] memory _candidateAddrs, address payable[] memory _newCandidateAddrs ) public returns(bool) { for (uint i=0;i < _candidateAddrs.length;i++) { require(updateCandidateAddrByIndex(index, _candidateAddrs[i],_newCandidateAddrs[i])); } return true; } function setHolderAddr( address payable _coinBase, address payable _holderAddr ) public returns(bool) { return setHolderAddrByIndex(nodeBallotAddrs.length - 1, _coinBase,_holderAddr); } function setHolderAddrByIndex( uint index, address payable _coinBase, address payable _holderAddr )onlyAdmin public returns(bool) { return _getVoteInterface(index).setHolderAddr(_coinBase,_holderAddr); } function batchSetHolderAddr( address payable[] memory _coinBases, address payable[] memory _holderAddrs ) public returns(bool) { return batchSetHolderAddrByIndex(nodeBallotAddrs.length - 1, _coinBases,_holderAddrs); } function batchSetHolderAddrByIndex( uint index, address payable[] memory _coinBases, address payable[] memory _holderAddrs ) public returns(bool) { for (uint i=0;i < _coinBases.length;i++) { require(setHolderAddrByIndex(index, _coinBases[i],_holderAddrs[i])); } return true; } function initHolderAddr( address payable _coinBase, address payable _holderAddr ) public returns(bool) { return initHolderAddrByIndex(nodeBallotAddrs.length - 1, _coinBase,_holderAddr); } function initHolderAddrByIndex( uint index, address payable _coinBase, address payable _holderAddr )onlyAdmin public returns(bool) { return _getAdminInterface(index).initHolderAddr(_coinBase,_holderAddr); } function batchInitHolderAddr( address payable[] memory _coinBases, address payable[] memory _holderAddrs ) public returns(bool) { return batchInitHolderAddrByIndex(nodeBallotAddrs.length - 1, _coinBases,_holderAddrs); } function batchInitHolderAddrByIndex( uint index, address payable[] memory _coinBases, address payable[] memory _holderAddrs ) public returns(bool) { for (uint i=0;i < _coinBases.length;i++) { require(initHolderAddrByIndex(index, _coinBases[i],_holderAddrs[i])); } return true; } function addCoinBase( address payable _coinBase ) public returns(bool) { return addCoinBaseByIndex(nodeBallotAddrs.length - 1, _coinBase); } function addCoinBaseByIndex( uint index, address payable _coinBase )onlyAdmin public returns(bool) { return _getAdminInterface(index).addCoinBase(_coinBase); } function batchAddCoinBase( address payable[] memory _coinBases ) public returns(bool) { return batchAddCoinBaseByIndex(nodeBallotAddrs.length - 1, _coinBases); } function batchAddCoinBaseByIndex( uint index, address payable[] memory _coinBases ) public returns(bool) { for (uint i=0;i < _coinBases.length;i++) { require(addCoinBaseByIndex(index,_coinBases[i])); } return true; } function updateCoinBase( address payable _coinBase, address payable _newCoinBase ) public returns(bool) { return updateCoinBaseByIndex(nodeBallotAddrs.length - 1, _coinBase, _newCoinBase); } function updateCoinBaseByIndex( uint index, address payable _coinBase, address payable _newCoinBase )onlyAdmin public returns(bool) { return _getVoteInterface(index).updateCoinBase(_coinBase, _newCoinBase); } function batchUpdateCoinBase( address payable[] memory _coinBases, address payable[] memory _newCoinBases ) public returns(bool) { return batchUpdateCoinBaseByIndex(nodeBallotAddrs.length - 1, _coinBases, _newCoinBases); } function batchUpdateCoinBaseByIndex( uint index, address payable[] memory _coinBases, address payable[] memory _newCoinBases ) public returns(bool) { for (uint i=0;i < _coinBases.length;i++) { require(updateCoinBaseByIndex(index, _coinBases[i], _newCoinBases[i])); } return true; } function calVoteResult() public returns(bool) { return calVoteResultByIndex(nodeBallotAddrs.length - 1); } function calVoteResultByIndex( uint index )onlyAdmin public returns(bool) { return _getAdminInterface(index).calVoteResult(); } /** * 投票 */ function vote( address payable candidateAddr, uint num ) public returns(bool) { return voteByIndex(nodeBallotAddrs.length - 1, candidateAddr, num) ; } function voteByIndex( uint index, address payable candidateAddr, uint num ) public returns(bool) { return _getVoteInterface(index).vote(msg.sender, candidateAddr, num); } /** * 用于批量投票 For non locked voting */ function batchVote( address payable[] memory candidateAddrs, uint[] memory nums ) public returns(bool) { return batchVoteByIndex(nodeBallotAddrs.length - 1, candidateAddrs, nums); } function batchVoteByIndex( uint index, address payable[] memory candidateAddrs, uint[] memory nums ) public returns(bool) { return _getVoteInterface(index).batchVote(msg.sender, candidateAddrs, nums); } function refreshVoteForAll() public returns(bool) { return refreshVoteForAllByIndex(nodeBallotAddrs.length - 1); } function refreshVoteForAllByIndex( uint index ) public returns(bool) { return _getVoteInterface(index).refreshVoteForAll(); } function batchRefreshVoteForVoter( address payable[] memory voterAddrs ) public returns(bool){ for (uint i=0;i < voterAddrs.length;i++) { refreshVoteForVoter(voterAddrs[i]); } return true; } function batchRefreshVoteForVoterByIndex( uint index, address payable[] memory voterAddrs ) public returns(bool){ for (uint i=0;i < voterAddrs.length;i++) { refreshVoteForVoterByIndex(index,voterAddrs[i]); } return true; } function refreshVoteForVoter( address payable voterAddr ) public returns(bool){ return refreshVoteForVoterByIndex(nodeBallotAddrs.length - 1,voterAddr); } function refreshVoteForVoterByIndex( uint index, address payable voterAddr ) public returns(bool) { return _getVoteInterface(index).refreshVoteForVoter(voterAddr); } /** * 撤回对某个候选人的投票 Withdraw a vote on a candidate. */ function cancelVoteForCandidate( address payable candidateAddr, uint num ) public returns(bool) { return cancelVoteForCandidateByIndex(nodeBallotAddrs.length - 1, candidateAddr, num); } function cancelVoteForCandidateByIndex( uint index, address payable candidateAddr, uint num ) public returns(bool) { return _getVoteInterface(index).cancelVoteForCandidate(msg.sender, candidateAddr, num); } function batchCancelVoteForCandidate( address payable[] memory candidateAddrs, uint[] memory nums ) public returns(bool) { return batchCancelVoteForCandidateByIndex(nodeBallotAddrs.length - 1, candidateAddrs, nums); } function batchCancelVoteForCandidateByIndex( uint index, address payable[] memory candidateAddrs, uint[] memory nums ) public returns(bool) { for (uint i=0;i < candidateAddrs.length;i++) { require(_getVoteInterface(index).cancelVoteForCandidate(msg.sender, candidateAddrs[i], nums[i])); } return true; } /** * 获取所有候选人的详细信息 */ function fetchAllCandidates() public view returns ( address payable[] memory ) { return fetchAllCandidatesByIndex(nodeBallotAddrs.length - 1); } function fetchAllCandidatesByIndex( uint index ) public view returns ( address payable[] memory ) { return _getFetchVoteInterface(index).fetchAllCandidates(); } function fetchAllVoterWithBalance() public view returns ( address payable[] memory, uint[] memory, uint[] memory ) { address payable[] memory _addrs; uint[] memory _voteNumbers; (_addrs,_voteNumbers)=fetchAllVoters(); uint cl=_addrs.length ; uint[] memory _voteBalances=new uint[](cl); for (uint i=0;i <cl;i++) { _voteBalances[i] = _addrs[i].balance; } return (_addrs, _voteNumbers,_voteBalances); } function getToRefreshResult() public view returns ( address payable[] memory ) { address payable[] memory _addrs; uint[] memory _voteNumbers; (_addrs,_voteNumbers)=fetchAllVoters(); uint j=0; for (uint i=0;i <_addrs.length;i++) { if(_voteNumbers[i]>_addrs[i].balance){ j++; } } address payable[] memory addrs=new address payable[](j); uint n=0; for (uint k=0;k <_addrs.length;k++) { if(_voteNumbers[k]>_addrs[k].balance){ addrs[n]=_addrs[k]; n++; } } return addrs; } function getToRefreshResultByIndex( uint index ) public view returns ( address payable[] memory ) { address payable[] memory _addrs; uint[] memory _voteNumbers; (_addrs,_voteNumbers)=fetchAllVotersByIndex(index); uint j=0; for (uint i=0;i <_addrs.length;i++) { if(_voteNumbers[i]>_addrs[i].balance){ j++; } } address payable[] memory addrs=new address payable[](j); uint n=0; for (uint k=0;k <_addrs.length;k++) { if(_voteNumbers[k]>_addrs[k].balance){ addrs[n]=_addrs[k]; n++; } } return addrs; } /** * 获取所有投票人的详细信息 */ function fetchAllVoters() public view returns ( address payable[] memory, uint[] memory ) { return fetchAllVotersByIndex(nodeBallotAddrs.length - 1); } function fetchAllVotersByIndex( uint index ) public view returns ( address payable[] memory, uint[] memory ) { return _getFetchVoteInterface(index).fetchAllVoters(); } /** * 获取所有投票人的投票情况 */ function fetchVoteInfoForVoter( address payable voterAddr ) public view returns ( address payable[] memory, uint[] memory ) { return fetchVoteInfoForVoterByIndex(nodeBallotAddrs.length - 1, voterAddr); } function fetchVoteInfoForVoterByIndex( uint index, address payable voterAddr ) public view returns ( address payable[] memory, uint[] memory ) { return _getFetchVoteInterface(index).fetchVoteInfoForVoter(voterAddr); } /** * 获取某个候选人的总得票数 * Total number of votes obtained from candidates */ function fetchVoteNumForCandidate( address payable candidateAddr ) public view returns (uint) { return fetchVoteNumForCandidateByIndex(nodeBallotAddrs.length - 1, candidateAddr); } function fetchVoteNumForCandidateByIndex( uint index, address payable candidateAddr ) public view returns (uint) { return _getFetchVoteInterface(index).fetchVoteNumForCandidate(candidateAddr); } /** * 获取某个投票人已投票数 * Total number of votes obtained from voterAddr */ function fetchVoteNumForVoter( address payable voterAddr ) public view returns (uint) { return fetchVoteNumForVoterByIndex(nodeBallotAddrs.length - 1, voterAddr); } function fetchVoteNumForVoterWithBalance( address payable voterAddr ) public view returns (uint,uint) { return (fetchVoteNumForVoter(voterAddr),voterAddr.balance); } function fetchVoteNumForVoterWithBalance( address payable[] memory voterAddrs ) public view returns ( uint[] memory, uint[] memory ) { uint cl=voterAddrs.length; uint[] memory _voteNumbers=new uint[](cl); uint[] memory _voteBalances=new uint[](cl); for(uint i=0;i<cl;i++){ _voteNumbers[i]=fetchVoteNumForVoter(voterAddrs[i]); _voteBalances[i]=voterAddrs[i].balance; } return (_voteNumbers,_voteBalances); } function fetchVoteNumForVoterByIndex( uint index, address payable voterAddr ) public view returns (uint) { return _getFetchVoteInterface(index).fetchVoteNumForVoter(voterAddr); } /** * 获取某个候选人被投票详细情况 */ function fetchVoteInfoForCandidate( address payable candidateAddr ) public view returns ( address payable[] memory, uint[] memory ) { return fetchVoteInfoForCandidateByIndex(nodeBallotAddrs.length - 1, candidateAddr); } function fetchVoteInfoForCandidateByIndex( uint index, address payable candidateAddr ) public view returns ( address payable[] memory, uint[] memory ) { return _getFetchVoteInterface(index).fetchVoteInfoForCandidate(candidateAddr); } function fetchVoteNumForVoterToCandidate( address payable voterAddr, address payable candidateAddr ) public view returns (uint){ return fetchVoteNumForVoterToCandidateByIndex(nodeBallotAddrs.length - 1,voterAddr,candidateAddr); } function fetchVoteNumForVoterToCandidateByIndex( uint index, address payable voterAddr, address payable candidateAddr ) public view returns (uint){ return _getFetchVoteInterface(index).fetchVoteNumForVoterToCandidate(voterAddr,candidateAddr); } function getHolderAddr( address payable _coinBase ) public view returns ( address payable ){ return getHolderAddrByIndex(nodeBallotAddrs.length - 1,_coinBase); } function getHolderAddrByIndex( uint index, address payable _coinBase ) public view returns ( address payable ){ return _getFetchVoteInterface(index).getHolderAddr(_coinBase); } function fetchAllHolderAddrsByIndex( uint index ) public view returns ( address payable[] memory, address payable[] memory ){ address payable[] memory coinbases=_getFetchVoteInterface(index).getAllCoinBases(); address payable[] memory holderAddrs=new address payable[](coinbases.length); for (uint i =0;i <coinbases.length;i++) { holderAddrs[i] =getHolderAddrByIndex(index,coinbases[i]); } return (coinbases,holderAddrs); } function fetchAllHolderAddrs( ) public view returns ( address payable[] memory, address payable[] memory ){ return fetchAllHolderAddrsByIndex(nodeBallotAddrs.length - 1); } function fetchAllVoteResult() public view returns ( address payable[] memory, uint[] memory ) { return fetchAllVoteResultByIndex(nodeBallotAddrs.length - 1); } function fetchAllVoteResultByIndex( uint index ) public view returns ( address payable [] memory, uint[] memory ) { return _getFetchVoteInterface(index).fetchAllVoteResult(); } function fetchResultForNodes() public view returns ( address payable[] memory, uint[] memory ) { if (FetchVoteInterface(nodeBallotAddrInService).isRunUpStage()) { return (new address payable[](0),new uint[](0)); } address payable[] memory _candidateAddrs; uint[] memory _nums; (_candidateAddrs,_nums) = FetchVoteInterface(nodeBallotAddrInService).fetchAllVoteResult(); if (_nums.length < 1) { return (new address payable[](0),new uint[](0)); } else { return (_candidateAddrs,_nums); } } function fetchAllHolderAddrsForNodes( ) public view returns ( address payable[] memory, address payable[] memory ){ if (FetchVoteInterface(nodeBallotAddrInService).isRunUpStage()) { return (new address payable[](0),new address payable[](0)); } address payable[] memory _coinbaseAddrs; address payable[] memory _holderAddrs; uint ballotIndex=nodeBallotIndex[nodeBallotAddrInService]; (_coinbaseAddrs,_holderAddrs)=fetchAllHolderAddrsByIndex(ballotIndex); if (_coinbaseAddrs.length < 1) { return (new address payable[](0),new address payable[](0)); } else { return (_coinbaseAddrs,_holderAddrs); } } function addHpbNodeBatch( address payable[] memory coinbases, bytes32[] memory cid1s, bytes32[] memory cid2s, bytes32[] memory hids )onlyAdmin public returns(bool) { return _getHpbNodesInterface().addHpbNodeBatch(coinbases, cid1s, cid2s, hids); } function addContractMethod( address _contractAddr, bytes4 _methodId )onlyAdmin public returns(bool){ return _getContractSimpleProxyInterface().addContractMethod(_contractAddr,_methodId); } function updateInvokeContract( uint invokeIndex, uint contractIndex, uint methodIdIndex )onlyAdmin public returns(bool){ return _getContractSimpleProxyInterface().updateInvokeContract(invokeIndex,contractIndex,methodIdIndex); } function getContractIndexAndMethodIndex( address _contractAddr, bytes4 _methodId )public view returns (uint,uint){ return _getContractSimpleProxyInterface().getContractIndexAndMethodIndex(_contractAddr,_methodId); } function getInvokeContract( uint invokeIndex ) public view returns (address,bytes4){ return _getContractSimpleProxyInterface().getInvokeContract(invokeIndex); } } contract HpbContractProxy is NodeBallotProx{ struct HpbNodeCache { address payable coinbase; bytes32 cid1; bytes32 cid2; bytes32 hid; } HpbNodeCache[] hpbNodeCacheArray; mapping (address => uint) hpbNodeCacheIndexMap; event ReceivedHpb( address payable indexed sender, uint amount ); // 接受HPB转账 function () payable external { emit ReceivedHpb( msg.sender, msg.value ); } // 销毁合约,并把合约余额返回给合约拥有者 function kill() onlyOwner payable public returns(bool) { selfdestruct(owner); return true; } function withdraw( uint _value ) onlyOwner payable public returns(bool) { require(address(this).balance >= _value); owner.transfer(_value); return true; } constructor () payable public { owner = msg.sender; adminMap[msg.sender] = msg.sender; nodeBallotAddrs.push(address(0)); hpbNodeCacheArray.push(HpbNodeCache(msg.sender, 0, 0, 0)); } function setHpbNodesAddress( address payable _hpbNodesAddress ) onlyAdmin public returns(bool) { hpbNodesAddress = _hpbNodesAddress; return true; } function setContractSimpleProxyAddress( address payable _contractSimpleProxyAddress ) onlyAdmin public returns(bool) { contractSimpleProxyAddress = _contractSimpleProxyAddress; return true; } function addNodeBallotAddress( address payable _nodeBallotAddress ) onlyAdmin public returns(bool) { require(nodeBallotIndex[_nodeBallotAddress] == 0); nodeBallotIndex[_nodeBallotAddress]=nodeBallotAddrs.push(_nodeBallotAddress) - 1; return true; } function updateNodeBallotAddress( address payable _nodeBallotAddress, address payable _newNodeBallotAddress ) onlyAdmin public returns(bool) { uint index=nodeBallotIndex[_nodeBallotAddress]; require(index != 0); nodeBallotAddrs[index] = _newNodeBallotAddress; nodeBallotIndex[_nodeBallotAddress] = 0; nodeBallotIndex[_newNodeBallotAddress] = index; return true; } function addNodesCache( address payable[] memory coinbases, bytes32[] memory cid1s, bytes32[] memory cid2s, bytes32[] memory hids ) onlyAdmin public returns(bool) { require(coinbases.length == cid1s.length); require(coinbases.length == cid2s.length); require(coinbases.length == hids.length); for (uint i = 0;i < coinbases.length;i++) { uint index = hpbNodeCacheIndexMap[coinbases[i]]; // 必须地址还未使用 require(index == 0); hpbNodeCacheIndexMap[coinbases[i]] = hpbNodeCacheArray.push( HpbNodeCache(coinbases[i],cid1s[i],cid2s[i],hids[i]) )-1; } return true; } function deleteHpbNodeCache( address payable coinbase ) onlyAdmin public returns(bool) { uint index = hpbNodeCacheIndexMap[coinbase]; // 必须地址存在 require(index != 0); delete hpbNodeCacheArray[index]; for (uint i = index;i < hpbNodeCacheArray.length - 1;i++) { hpbNodeCacheArray[i] = hpbNodeCacheArray[i+1]; hpbNodeCacheIndexMap[hpbNodeCacheArray[i].coinbase] = i; } delete hpbNodeCacheArray[hpbNodeCacheArray.length - 1]; hpbNodeCacheArray.length--; hpbNodeCacheIndexMap[coinbase] = 0; delete hpbNodeCacheIndexMap[coinbase]; return true; } function clearHpbNodeCache(address payable[] memory _coinbases) onlyAdmin public returns(bool) { require(hpbNodeCacheArray.length > 1); for (uint j = 0;j < _coinbases.length;j++) { require(deleteHpbNodeCache(_coinbases[j])); } return true; } function getAllHpbNodesCache() public view returns ( address payable[] memory, bytes32[] memory, bytes32[] memory, bytes32[] memory ) { require(hpbNodeCacheArray.length > 1); uint cl=hpbNodeCacheArray.length - 1; address payable[] memory _coinbases=new address payable[](cl); bytes32[] memory _cid1s=new bytes32[](cl); bytes32[] memory _cid2s=new bytes32[](cl); bytes32[] memory _hids=new bytes32[](cl); for (uint i = 1;i < hpbNodeCacheArray.length;i++) { _coinbases[i-1] = hpbNodeCacheArray[i].coinbase; _cid1s[i-1] = hpbNodeCacheArray[i].cid1; _cid2s[i-1] = hpbNodeCacheArray[i].cid2; _hids[i-1] = hpbNodeCacheArray[i].hid; } return (_coinbases, _cid1s,_cid2s,_hids); } function switchNodes( bytes4 _methodId2, bytes4 _methodId3 ) onlyAdmin public returns(bool) { require(hpbNodeCacheArray.length > 1); uint cl=hpbNodeCacheArray.length - 1; address payable[] memory _coinbases=new address payable[](cl); bytes32[] memory _cid1s=new bytes32[](cl); bytes32[] memory _cid2s=new bytes32[](cl); bytes32[] memory _hids=new bytes32[](cl); for (uint i = 1;i < hpbNodeCacheArray.length;i++) { _coinbases[i-1] = hpbNodeCacheArray[i].coinbase; _cid1s[i-1] = hpbNodeCacheArray[i].cid1; _cid2s[i-1] = hpbNodeCacheArray[i].cid2; _hids[i-1] = hpbNodeCacheArray[i].hid; } require(_getHpbNodesInterface().addStage()); require(_getHpbNodesInterface().addHpbNodeBatch(_coinbases, _cid1s, _cid2s, _hids)); nodeBallotAddrInService = nodeBallotAddrs[nodeBallotAddrs.length-1]; address _contractAddr=address(this); if(_methodId2==bytes4(0)){ _methodId2=bytes4(keccak256("fetchResultForNodes()")); } address _oldContractAddr; bytes4 _oldMethodId2; (_oldContractAddr,_oldMethodId2)=getInvokeContract(2); if(_oldContractAddr!=_contractAddr||_oldMethodId2!=_methodId2){ require(addContractMethod(_contractAddr,_methodId2)); uint contractIndex2; uint methodIdIndex2; (contractIndex2,methodIdIndex2)=getContractIndexAndMethodIndex(_contractAddr,_methodId2); require(updateInvokeContract(2,contractIndex2,methodIdIndex2)); } if(_methodId3==bytes4(0)){ _methodId3=bytes4(keccak256("fetchAllHolderAddrsForNodes()")); } bytes4 _oldMethodId3; (_oldContractAddr,_oldMethodId3)=getInvokeContract(3); if(_oldContractAddr!=_contractAddr||_oldMethodId3!=_methodId3){ require(addContractMethod(_contractAddr,_methodId3)); uint contractIndex3; uint methodIdIndex3; (contractIndex3,methodIdIndex3)=getContractIndexAndMethodIndex(_contractAddr,_methodId3); require(updateInvokeContract(3,contractIndex3,methodIdIndex3)); } } }
Integer division of two numbers, truncating the quotient./ 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
function div( uint256 a, uint256 b ) internal pure returns ( uint256 ) { return a / b; }
12,882,382
./full_match/1/0x929C3811906F006AD50Dbd5a104b1C17eEA85767/sources/contracts/TropyverseLand.sol
this function is for minting without any referral agent code
function mint( string[] memory _assets, string memory _nonce, bytes calldata _signature ) external payable mintCompliance(_assets) { require(!usedNonce[_nonce], INVALID_SIGNATURE); require( verifySignature(msg.sender, _assets, msg.value, _nonce, _signature), INVALID_SIGNATURE ); uint256 _managerPart = msg.value / 100; _mintLoop(_msgSender(), msg.value, _assets); sendEth(payable(manager), _managerPart); ReferralProgram ref = ReferralProgram(referralProgram); ref.updateTransferHistory(manager, _managerPart); addressMintedBalance[_msgSender()] += _assets.length; usedNonce[_nonce] = true; }
3,063,416
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (governor) that can be granted exclusive access to * specific functions. * * By default, the governor account will be the one that deploys the contract. This * can later be changed with {transferGovernorship}. * */ contract Governed is Context, Initializable { address public governor; address private proposedGovernor; event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor); /** * @dev Initializes the contract setting the deployer as the initial governor. */ constructor() { address msgSender = _msgSender(); governor = msgSender; emit UpdatedGovernor(address(0), msgSender); } /** * @dev If inheriting child is using proxy then child contract can use * _initializeGoverned() function to initialization this contract */ function _initializeGoverned() internal initializer { address msgSender = _msgSender(); governor = msgSender; emit UpdatedGovernor(address(0), msgSender); } /** * @dev Throws if called by any account other than the governor. */ modifier onlyGovernor { require(governor == _msgSender(), "not-the-governor"); _; } /** * @dev Transfers governorship of the contract to a new account (`proposedGovernor`). * Can only be called by the current owner. */ function transferGovernorship(address _proposedGovernor) external onlyGovernor { require(_proposedGovernor != address(0), "proposed-governor-is-zero"); proposedGovernor = _proposedGovernor; } /** * @dev Allows new governor to accept governorship of the contract. */ function acceptGovernorship() external { require(proposedGovernor == _msgSender(), "not-the-proposed-governor"); emit UpdatedGovernor(governor, proposedGovernor); governor = proposedGovernor; proposedGovernor = address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * */ contract Pausable is Context { event Paused(address account); event Shutdown(address account); event Unpaused(address account); event Open(address account); bool public paused; bool public stopEverything; modifier whenNotPaused() { require(!paused, "paused"); _; } modifier whenPaused() { require(paused, "not-paused"); _; } modifier whenNotShutdown() { require(!stopEverything, "shutdown"); _; } modifier whenShutdown() { require(stopEverything, "not-shutdown"); _; } /// @dev Pause contract operations, if contract is not paused. function _pause() internal virtual whenNotPaused { paused = true; emit Paused(_msgSender()); } /// @dev Unpause contract operations, allow only if contract is paused and not shutdown. function _unpause() internal virtual whenPaused whenNotShutdown { paused = false; emit Unpaused(_msgSender()); } /// @dev Shutdown contract operations, if not already shutdown. function _shutdown() internal virtual whenNotShutdown { stopEverything = true; paused = true; emit Shutdown(_msgSender()); } /// @dev Open contract operations, if contract is in shutdown state function _open() internal virtual whenShutdown { stopEverything = false; emit Open(_msgSender()); } } // 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]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface TokenLike is IERC20 { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolAccountant { function decreaseDebt(address _strategy, uint256 _decreaseBy) external; function migrateStrategy(address _old, address _new) external; function reportEarning( address _strategy, uint256 _profit, uint256 _loss, uint256 _payback ) external returns ( uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee ); function reportLoss(address _strategy, uint256 _loss) external; function availableCreditLimit(address _strategy) external view returns (uint256); function excessDebt(address _strategy) external view returns (uint256); function getStrategies() external view returns (address[] memory); function getWithdrawQueue() external view returns (address[] memory); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio, uint256 _externalDepositFee ); function externalDepositFee() external view returns (uint256); function totalDebt() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalDebtRatio() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolRewards { /// Emitted after reward added event RewardAdded(address indexed rewardToken, uint256 reward, uint256 rewardDuration); /// Emitted whenever any user claim rewards event RewardPaid(address indexed user, address indexed rewardToken, uint256 reward); /// Emitted after adding new rewards token into rewardTokens array event RewardTokenAdded(address indexed rewardToken, address[] existingRewardTokens); function claimReward(address) external; function notifyRewardAmount( address _rewardToken, uint256 _rewardAmount, uint256 _rewardDuration ) external; function notifyRewardAmount( address[] memory _rewardTokens, uint256[] memory _rewardAmounts, uint256[] memory _rewardDurations ) external; function updateReward(address) external; function claimable(address _account) external view returns (address[] memory _rewardTokens, uint256[] memory _claimableAmounts); function lastTimeRewardApplicable(address _rewardToken) external view returns (uint256); function rewardForDuration() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardForDuration); function rewardPerToken() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardPerTokenRate); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function keepers() external view returns (address[] memory); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function totalValueCurrent() external returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /// @title Errors library library Errors { string public constant INVALID_COLLATERAL_AMOUNT = "1"; // Collateral must be greater than 0 string public constant INVALID_SHARE_AMOUNT = "2"; // Share must be greater than 0 string public constant INVALID_INPUT_LENGTH = "3"; // Input array length must be greater than 0 string public constant INPUT_LENGTH_MISMATCH = "4"; // Input array length mismatch with another array length string public constant NOT_WHITELISTED_ADDRESS = "5"; // Caller is not whitelisted to withdraw without fee string public constant MULTI_TRANSFER_FAILED = "6"; // Multi transfer of tokens has failed string public constant FEE_COLLECTOR_NOT_SET = "7"; // Fee Collector is not set string public constant NOT_ALLOWED_TO_SWEEP = "8"; // Token is not allowed to sweep string public constant INSUFFICIENT_BALANCE = "9"; // Insufficient balance to performs operations to follow string public constant INPUT_ADDRESS_IS_ZERO = "10"; // Input address is zero string public constant FEE_LIMIT_REACHED = "11"; // Fee must be less than MAX_BPS string public constant ALREADY_INITIALIZED = "12"; // Data structure, contract, or logic already initialized and can not be called again string public constant ADD_IN_LIST_FAILED = "13"; // Cannot add address in address list string public constant REMOVE_FROM_LIST_FAILED = "14"; // Cannot remove address from address list string public constant STRATEGY_IS_ACTIVE = "15"; // Strategy is already active, an inactive strategy is required string public constant STRATEGY_IS_NOT_ACTIVE = "16"; // Strategy is not active, an active strategy is required string public constant INVALID_STRATEGY = "17"; // Given strategy is not a strategy of this pool string public constant DEBT_RATIO_LIMIT_REACHED = "18"; // Debt ratio limit reached. It must be less than MAX_BPS string public constant TOTAL_DEBT_IS_NOT_ZERO = "19"; // Strategy total debt must be 0 string public constant LOSS_TOO_HIGH = "20"; // Strategy reported loss must be less than current debt } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; // solhint-disable reason-string, no-empty-blocks ///@title Pool ERC20 to use with proxy. Inspired by OpenZeppelin ERC20 abstract contract PoolERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. */ 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 decimals of the token. default to 18 */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev Returns total supply of the token. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _setName(string memory name_) internal { _name = name_; } function _setSymbol(string memory symbol_) internal { _symbol = symbol_; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./PoolERC20.sol"; ///@title Pool ERC20 Permit to use with proxy. Inspired by OpenZeppelin ERC20Permit // solhint-disable var-name-mixedcase abstract contract PoolERC20Permit is PoolERC20, IERC20Permit { bytes32 private constant _EIP712_VERSION = keccak256(bytes("1")); bytes32 private constant _EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private _CACHED_DOMAIN_SEPARATOR; bytes32 private _HASHED_NAME; uint256 private _CACHED_CHAIN_ID; /** * @dev See {IERC20Permit-nonces}. */ mapping(address => uint256) public override nonces; /** * @dev Initializes the domain separator using the `name` parameter, and setting `version` to `"1"`. * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function _initializePermit(string memory name_) internal { _HASHED_NAME = keccak256(bytes(name_)); _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); uint256 _currentNonce = nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _currentNonce, deadline)); bytes32 hash = keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); nonces[owner] = _currentNonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() private view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./PoolERC20Permit.sol"; import "./PoolStorage.sol"; import "./Errors.sol"; import "../Governed.sol"; import "../Pausable.sol"; import "../interfaces/vesper/IPoolAccountant.sol"; import "../interfaces/vesper/IPoolRewards.sol"; /// @title Holding pool share token // solhint-disable no-empty-blocks abstract contract PoolShareToken is Initializable, PoolERC20Permit, Governed, Pausable, ReentrancyGuard, PoolStorageV2 { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; uint256 public constant MAX_BPS = 10_000; event Deposit(address indexed owner, uint256 shares, uint256 amount); event Withdraw(address indexed owner, uint256 shares, uint256 amount); // We are using constructor to initialize implementation with basic details constructor( string memory _name, string memory _symbol, address _token ) PoolERC20(_name, _symbol) { // 0x0 is acceptable as has no effect on functionality token = IERC20(_token); } /// @dev Equivalent to constructor for proxy. It can be called only once per proxy. function _initializePool( string memory _name, string memory _symbol, address _token ) internal initializer { require(_token != address(0), Errors.INPUT_ADDRESS_IS_ZERO); _setName(_name); _setSymbol(_symbol); _initializePermit(_name); token = IERC20(_token); // Assuming token supports 18 or less decimals uint256 _decimals = IERC20Metadata(_token).decimals(); decimalConversionFactor = 10**(18 - _decimals); } /** * @notice Deposit ERC20 tokens and receive pool shares depending on the current share price. * @param _amount ERC20 token amount. */ function deposit(uint256 _amount) external virtual nonReentrant whenNotPaused { _updateRewards(_msgSender()); _deposit(_amount); } /** * @notice Deposit ERC20 tokens and claim rewards if any * @param _amount ERC20 token amount. */ function depositAndClaim(uint256 _amount) external virtual nonReentrant whenNotPaused { _depositAndClaim(_amount); } /** * @notice Deposit ERC20 tokens with permit aka gasless approval. * @param _amount ERC20 token amount. * @param _deadline The time at which signature will expire * @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 depositWithPermit( uint256 _amount, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external virtual nonReentrant whenNotPaused { IERC20Permit(address(token)).permit(_msgSender(), address(this), _amount, _deadline, _v, _r, _s); _deposit(_amount); } /** * @notice Withdraw collateral based on given shares and the current share price. * Withdraw fee, if any, will be deduced from given shares and transferred to feeCollector. * Burn remaining shares and return collateral. * @param _shares Pool shares. It will be in 18 decimals. */ function withdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown { _updateRewards(_msgSender()); _withdraw(_shares); } /** * @notice Withdraw collateral and claim rewards if any * @param _shares Pool shares. It will be in 18 decimals. */ function withdrawAndClaim(uint256 _shares) external virtual nonReentrant whenNotShutdown { _withdrawAndClaim(_shares); } /** * @notice Withdraw collateral based on given shares and the current share price. * @dev Burn shares and return collateral. No withdraw fee will be assessed * when this function is called. Only some white listed address can call this function. * @param _shares Pool shares. It will be in 18 decimals. * This function is deprecated, normal withdraw will check for whitelisted address */ function whitelistedWithdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown { require(_feeWhitelist.contains(_msgSender()), Errors.NOT_WHITELISTED_ADDRESS); require(_shares != 0, Errors.INVALID_SHARE_AMOUNT); _claimRewards(_msgSender()); _withdrawWithoutFee(_shares); } /** * @notice Transfer tokens to multiple recipient * @dev Address array and amount array are 1:1 and are in order. * @param _recipients array of recipient addresses * @param _amounts array of token amounts * @return true/false */ function multiTransfer(address[] calldata _recipients, uint256[] calldata _amounts) external returns (bool) { require(_recipients.length == _amounts.length, Errors.INPUT_LENGTH_MISMATCH); for (uint256 i = 0; i < _recipients.length; i++) { require(transfer(_recipients[i], _amounts[i]), Errors.MULTI_TRANSFER_FAILED); } return true; } /** * @notice Get price per share * @dev Return value will be in token defined decimals. */ function pricePerShare() public view returns (uint256) { if (totalSupply() == 0 || totalValue() == 0) { return convertFrom18(1e18); } return (totalValue() * 1e18) / totalSupply(); } /** * @notice Calculate how much shares user will get for given amount. Also return externalDepositFee if any. * @param _amount Collateral amount * @return _shares Amount of share that user will get */ function calculateMintage(uint256 _amount) public view returns (uint256 _shares) { require(_amount != 0, Errors.INVALID_COLLATERAL_AMOUNT); uint256 _externalDepositFee = (_amount * IPoolAccountant(poolAccountant).externalDepositFee()) / MAX_BPS; _shares = _calculateShares(_amount - _externalDepositFee); } /// @dev Convert from 18 decimals to token defined decimals. function convertFrom18(uint256 _amount) public view virtual returns (uint256) { return _amount / decimalConversionFactor; } /// @dev Returns the token stored in the pool. It will be in token defined decimals. function tokensHere() public view virtual returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Returns sum of token locked in other contracts and token stored in the pool. * Default tokensHere. It will be in token defined decimals. */ function totalValue() public view virtual returns (uint256); /** * @dev Hook that is called just before burning tokens. This withdraw collateral from withdraw queue * @param _share Pool share in 18 decimals */ function _beforeBurning(uint256 _share) internal virtual returns (uint256) {} /** * @dev Hook that is called just after burning tokens. * @param _amount Collateral amount in collateral token defined decimals. */ function _afterBurning(uint256 _amount) internal virtual returns (uint256) { token.safeTransfer(_msgSender(), _amount); return _amount; } /** * @dev Hook that is called just before minting new tokens. To be used i.e. * if the deposited amount is to be transferred from user to this contract. * @param _amount Collateral amount in collateral token defined decimals. */ function _beforeMinting(uint256 _amount) internal virtual { token.safeTransferFrom(_msgSender(), address(this), _amount); } /** * @dev Hook that is called just after minting new tokens. To be used i.e. * if the deposited amount is to be transferred to a different contract. * @param _amount Collateral amount in collateral token defined decimals. */ function _afterMinting(uint256 _amount) internal virtual {} /// @dev Update pool rewards of sender and receiver during transfer. function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { if (poolRewards != address(0)) { IPoolRewards(poolRewards).updateReward(sender); IPoolRewards(poolRewards).updateReward(recipient); } super._transfer(sender, recipient, amount); } /** * @dev Calculate shares to mint/burn based on the current share price and given amount. * @param _amount Collateral amount in collateral token defined decimals. * @return share amount in 18 decimal */ function _calculateShares(uint256 _amount) internal view returns (uint256) { uint256 _share = ((_amount * 1e18) / pricePerShare()); return _amount > ((_share * pricePerShare()) / 1e18) ? _share + 1 : _share; } /// @notice claim rewards of account function _claimRewards(address _account) internal { if (poolRewards != address(0)) { IPoolRewards(poolRewards).claimReward(_account); } } function _updateRewards(address _account) internal { if (poolRewards != address(0)) { IPoolRewards(poolRewards).updateReward(_account); } } /// @dev Deposit incoming token and mint pool token i.e. shares. function _deposit(uint256 _amount) internal virtual { uint256 _shares = calculateMintage(_amount); _beforeMinting(_amount); _mint(_msgSender(), _shares); _afterMinting(_amount); emit Deposit(_msgSender(), _shares, _amount); } /// @dev Deposit token and claim rewards if any function _depositAndClaim(uint256 _amount) internal { _claimRewards(_msgSender()); _deposit(_amount); } /// @dev Burns shares and returns the collateral value, after fee, of those. function _withdraw(uint256 _shares) internal virtual { require(_shares != 0, Errors.INVALID_SHARE_AMOUNT); if (withdrawFee == 0 || _feeWhitelist.contains(_msgSender())) { _withdrawWithoutFee(_shares); } else { uint256 _fee = (_shares * withdrawFee) / MAX_BPS; uint256 _sharesAfterFee = _shares - _fee; uint256 _amountWithdrawn = _beforeBurning(_sharesAfterFee); // Recalculate proportional share on actual amount withdrawn uint256 _proportionalShares = _calculateShares(_amountWithdrawn); // Using convertFrom18() to avoid dust. // Pool share token is in 18 decimal and collateral token decimal is <=18. // Anything less than 10**(18-collateralTokenDecimal) is dust. if (convertFrom18(_proportionalShares) < convertFrom18(_sharesAfterFee)) { // Recalculate shares to withdraw, fee and shareAfterFee _shares = (_proportionalShares * MAX_BPS) / (MAX_BPS - withdrawFee); _fee = _shares - _proportionalShares; _sharesAfterFee = _proportionalShares; } _burn(_msgSender(), _sharesAfterFee); _transfer(_msgSender(), feeCollector, _fee); _afterBurning(_amountWithdrawn); emit Withdraw(_msgSender(), _shares, _amountWithdrawn); } } /// @dev Withdraw collateral and claim rewards if any function _withdrawAndClaim(uint256 _shares) internal { _claimRewards(_msgSender()); _withdraw(_shares); } /// @dev Burns shares and returns the collateral value of those. function _withdrawWithoutFee(uint256 _shares) internal { uint256 _amountWithdrawn = _beforeBurning(_shares); uint256 _proportionalShares = _calculateShares(_amountWithdrawn); if (convertFrom18(_proportionalShares) < convertFrom18(_shares)) { _shares = _proportionalShares; } _burn(_msgSender(), _shares); _afterBurning(_amountWithdrawn); emit Withdraw(_msgSender(), _shares, _amountWithdrawn); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract PoolStorageV1 { IERC20 public token; // Collateral token address public poolAccountant; // PoolAccountant address address public poolRewards; // PoolRewards contract address address private feeWhitelistObsolete; // Obsolete in favor of AddressSet of feeWhitelist address private keepersObsolete; // Obsolete in favor of AddressSet of keepers address private maintainersObsolete; // Obsolete in favor of AddressSet of maintainers address public feeCollector; // Fee collector address uint256 public withdrawFee; // Withdraw fee for this pool uint256 public decimalConversionFactor; // It can be used in converting value to/from 18 decimals bool internal withdrawInETH; // This flag will be used by VETH pool as switch to withdraw ETH or WETH } contract PoolStorageV2 is PoolStorageV1 { EnumerableSet.AddressSet internal _feeWhitelist; // List of addresses whitelisted for feeless withdraw EnumerableSet.AddressSet internal _keepers; // List of keeper addresses EnumerableSet.AddressSet internal _maintainers; // List of maintainer addresses } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./VPool.sol"; import "../interfaces/token/IToken.sol"; //solhint-disable no-empty-blocks contract VETH is VPool { constructor( string memory _name, string memory _symbol, address _token ) VPool(_name, _symbol, _token) {} /// @dev Handle incoming ETH to the contract address. receive() external payable { if (msg.sender != address(token)) { deposit(); } } /// @dev Burns tokens/shares and returns the ETH value, after fee, of those. function withdrawETH(uint256 _shares) external whenNotShutdown nonReentrant { withdrawInETH = true; _updateRewards(_msgSender()); _withdraw(_shares); withdrawInETH = false; } /// @dev Burns tokens/shares and returns the ETH value and claim rewards if any function withdrawETHAndClaim(uint256 _shares) external whenNotShutdown nonReentrant { withdrawInETH = true; _withdrawAndClaim(_shares); withdrawInETH = false; } /** * @dev After burning hook, it will be called during withdrawal process. * It will withdraw collateral from strategy and transfer it to user. */ function _afterBurning(uint256 _amount) internal override returns (uint256) { if (withdrawInETH) { TokenLike(address(token)).withdraw(_amount); Address.sendValue(payable(_msgSender()), _amount); } else { super._afterBurning(_amount); } return _amount; } /** * @dev Receives ETH and grants new tokens/shares to the sender depending * on the value of pool's share. */ function deposit() public payable whenNotPaused nonReentrant { _updateRewards(_msgSender()); _deposit(); } /// @dev Deposit ETH and claim rewards if any function depositAndClaim() external payable whenNotPaused nonReentrant { _claimRewards(_msgSender()); _deposit(); } function _deposit() internal { uint256 _shares = calculateMintage(msg.value); // Wraps ETH in WETH TokenLike(address(token)).deposit{value: msg.value}(); _mint(_msgSender(), _shares); emit Deposit(_msgSender(), _shares, msg.value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./VPoolBase.sol"; //solhint-disable no-empty-blocks contract VPool is VPoolBase { string public constant VERSION = "4.0.0"; constructor( string memory _name, string memory _symbol, address _token ) VPoolBase(_name, _symbol, _token) {} function initialize( string memory _name, string memory _symbol, address _token, address _poolAccountant ) public initializer { _initializeBase(_name, _symbol, _token, _poolAccountant); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./Errors.sol"; import "./PoolShareToken.sol"; import "../interfaces/vesper/IStrategy.sol"; abstract contract VPoolBase is PoolShareToken { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedPoolRewards(address indexed previousPoolRewards, address indexed newPoolRewards); event UpdatedWithdrawFee(uint256 previousWithdrawFee, uint256 newWithdrawFee); constructor( string memory _name, string memory _symbol, address _token // solhint-disable-next-line no-empty-blocks ) PoolShareToken(_name, _symbol, _token) {} /// @dev Equivalent to constructor for proxy. It can be called only once per proxy. function _initializeBase( string memory _name, string memory _symbol, address _token, address _poolAccountant ) internal initializer { require(_poolAccountant != address(0), Errors.INPUT_ADDRESS_IS_ZERO); _initializePool(_name, _symbol, _token); _initializeGoverned(); require(_keepers.add(_msgSender()), Errors.ADD_IN_LIST_FAILED); require(_maintainers.add(_msgSender()), Errors.ADD_IN_LIST_FAILED); poolAccountant = _poolAccountant; } modifier onlyKeeper() { require(governor == _msgSender() || _keepers.contains(_msgSender()), "not-a-keeper"); _; } modifier onlyMaintainer() { require(governor == _msgSender() || _maintainers.contains(_msgSender()), "not-a-maintainer"); _; } ////////////////////////////// Only Governor ////////////////////////////// /** * @notice Migrate existing strategy to new strategy. * @dev Migrating strategy aka old and new strategy should be of same type. * @param _old Address of strategy being migrated * @param _new Address of new strategy */ function migrateStrategy(address _old, address _new) external onlyGovernor { require( IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this), Errors.INVALID_STRATEGY ); IPoolAccountant(poolAccountant).migrateStrategy(_old, _new); IStrategy(_old).migrate(_new); } /** * @notice Update fee collector address for this pool * @param _newFeeCollector new fee collector address */ function updateFeeCollector(address _newFeeCollector) external onlyGovernor { require(_newFeeCollector != address(0), Errors.INPUT_ADDRESS_IS_ZERO); emit UpdatedFeeCollector(feeCollector, _newFeeCollector); feeCollector = _newFeeCollector; } /** * @notice Update pool rewards address for this pool * @param _newPoolRewards new pool rewards address */ function updatePoolRewards(address _newPoolRewards) external onlyGovernor { require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO); emit UpdatedPoolRewards(poolRewards, _newPoolRewards); poolRewards = _newPoolRewards; } /** * @notice Update withdraw fee for this pool * @dev Format: 1500 = 15% fee, 100 = 1% * @param _newWithdrawFee new withdraw fee */ function updateWithdrawFee(uint256 _newWithdrawFee) external onlyGovernor { require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET); require(_newWithdrawFee <= MAX_BPS, Errors.FEE_LIMIT_REACHED); emit UpdatedWithdrawFee(withdrawFee, _newWithdrawFee); withdrawFee = _newWithdrawFee; } ///////////////////////////// Only Keeper /////////////////////////////// function pause() external onlyKeeper { _pause(); } function unpause() external onlyKeeper { _unpause(); } function shutdown() external onlyKeeper { _shutdown(); } function open() external onlyKeeper { _open(); } /// @notice Return list of whitelisted addresses function feeWhitelist() external view returns (address[] memory) { return _feeWhitelist.values(); } function isFeeWhitelisted(address _address) external view returns (bool) { return _feeWhitelist.contains(_address); } /** * @notice Add given address in feeWhitelist. * @param _addressToAdd Address to add in feeWhitelist. */ function addToFeeWhitelist(address _addressToAdd) external onlyKeeper { require(_feeWhitelist.add(_addressToAdd), Errors.ADD_IN_LIST_FAILED); } /** * @notice Remove given address from feeWhitelist. * @param _addressToRemove Address to remove from feeWhitelist. */ function removeFromFeeWhitelist(address _addressToRemove) external onlyKeeper { require(_feeWhitelist.remove(_addressToRemove), Errors.REMOVE_FROM_LIST_FAILED); } /// @notice Return list of keepers function keepers() external view returns (address[] memory) { return _keepers.values(); } function isKeeper(address _address) external view returns (bool) { return _keepers.contains(_address); } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyKeeper { require(_keepers.add(_keeperAddress), Errors.ADD_IN_LIST_FAILED); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyKeeper { require(_keepers.remove(_keeperAddress), Errors.REMOVE_FROM_LIST_FAILED); } /// @notice Return list of maintainers function maintainers() external view returns (address[] memory) { return _maintainers.values(); } function isMaintainer(address _address) external view returns (bool) { return _maintainers.contains(_address); } /** * @notice Add given address in maintainers list. * @param _maintainerAddress maintainer address to add. */ function addMaintainer(address _maintainerAddress) external onlyKeeper { require(_maintainers.add(_maintainerAddress), Errors.ADD_IN_LIST_FAILED); } /** * @notice Remove given address from maintainers list. * @param _maintainerAddress maintainer address to remove. */ function removeMaintainer(address _maintainerAddress) external onlyKeeper { require(_maintainers.remove(_maintainerAddress), Errors.REMOVE_FROM_LIST_FAILED); } /////////////////////////////////////////////////////////////////////////// /** * @dev Strategy call this in regular interval. * @param _profit yield generated by strategy. Strategy get performance fee on this amount * @param _loss Reduce debt ,also reduce debtRatio, increase loss in record. * @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount. * when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately. */ function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) public virtual { (uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee) = IPoolAccountant(poolAccountant).reportEarning(_msgSender(), _profit, _loss, _payback); uint256 _totalPayback = _profit + _actualPayback; // After payback, if strategy has credit line available then send more fund to strategy // If payback is more than available credit line then get fund from strategy if (_totalPayback < _creditLine) { token.safeTransfer(_msgSender(), _creditLine - _totalPayback); } else if (_totalPayback > _creditLine) { token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine); } // Mint interest fee worth shares at feeCollector address if (_interestFee != 0) { _mint(IStrategy(_msgSender()).feeCollector(), _calculateShares(_interestFee)); } } /** * @notice Report loss outside of rebalance activity. * @dev Some strategies pay deposit fee thus realizing loss at deposit. * For example: Curve's 3pool has some slippage due to deposit of one asset in 3pool. * Strategy may want report this loss instead of waiting for next rebalance. * @param _loss Loss that strategy want to report */ function reportLoss(uint256 _loss) external { if (_loss != 0) { IPoolAccountant(poolAccountant).reportLoss(_msgSender(), _loss); } } /** * @dev Transfer given ERC20 token to feeCollector * @param _fromToken Token address to sweep */ function sweepERC20(address _fromToken) external virtual onlyKeeper { require(_fromToken != address(token), Errors.NOT_ALLOWED_TO_SWEEP); require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET); IERC20(_fromToken).safeTransfer(feeCollector, IERC20(_fromToken).balanceOf(address(this))); } /** * @notice Get available credit limit of strategy. This is the amount strategy can borrow from pool * @dev Available credit limit is calculated based on current debt of pool and strategy, current debt limit of pool and strategy. * credit available = min(pool's debt limit, strategy's debt limit, max debt per rebalance) * when some strategy do not pay back outstanding debt, this impact credit line of other strategy if totalDebt of pool >= debtLimit of pool * @param _strategy Strategy address */ function availableCreditLimit(address _strategy) external view returns (uint256) { return IPoolAccountant(poolAccountant).availableCreditLimit(_strategy); } /** * @notice Debt above current debt limit * @param _strategy Address of strategy */ function excessDebt(address _strategy) external view returns (uint256) { return IPoolAccountant(poolAccountant).excessDebt(_strategy); } function getStrategies() public view returns (address[] memory) { return IPoolAccountant(poolAccountant).getStrategies(); } function getWithdrawQueue() public view returns (address[] memory) { return IPoolAccountant(poolAccountant).getWithdrawQueue(); } function strategy(address _strategy) public view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio, uint256 _externalDepositFee ) { return IPoolAccountant(poolAccountant).strategy(_strategy); } /// @notice Get total debt of pool function totalDebt() external view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebt(); } /** * @notice Get total debt of given strategy * @param _strategy Strategy address */ function totalDebtOf(address _strategy) public view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebtOf(_strategy); } /// @notice Get total debt ratio. Total debt ratio helps us keep buffer in pool function totalDebtRatio() external view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebtRatio(); } /// @dev Returns total value of vesper pool, in terms of collateral token function totalValue() public view override returns (uint256) { return IPoolAccountant(poolAccountant).totalDebt() + tokensHere(); } function _withdrawCollateral(uint256 _amount) internal virtual { // Withdraw amount from queue uint256 _debt; uint256 _balanceAfter; uint256 _balanceBefore; uint256 _amountWithdrawn; uint256 _totalAmountWithdrawn; address[] memory _withdrawQueue = getWithdrawQueue(); uint256 _len = _withdrawQueue.length; for (uint256 i; i < _len; i++) { uint256 _amountNeeded = _amount - _totalAmountWithdrawn; address _strategy = _withdrawQueue[i]; _debt = totalDebtOf(_strategy); if (_debt == 0) { continue; } if (_amountNeeded > _debt) { // Should not withdraw more than current debt of strategy. _amountNeeded = _debt; } _balanceBefore = tokensHere(); //solhint-disable no-empty-blocks try IStrategy(_strategy).withdraw(_amountNeeded) {} catch { continue; } _balanceAfter = tokensHere(); _amountWithdrawn = _balanceAfter - _balanceBefore; // Adjusting totalDebt. Assuming that during next reportEarning(), strategy will report loss if amountWithdrawn < _amountNeeded IPoolAccountant(poolAccountant).decreaseDebt(_strategy, _amountWithdrawn); _totalAmountWithdrawn += _amountWithdrawn; if (_totalAmountWithdrawn >= _amount) { // withdraw done break; } } } /** * @dev Before burning hook. * withdraw amount from strategies */ function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) { uint256 _amount = (_share * pricePerShare()) / 1e18; uint256 _balanceNow = tokensHere(); if (_amount > _balanceNow) { _withdrawCollateral(_amount - _balanceNow); _balanceNow = tokensHere(); } actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount; require(actualWithdrawn != 0, Errors.INVALID_COLLATERAL_AMOUNT); } }
Deposit ETH and claim rewards if any
function depositAndClaim() external payable whenNotPaused nonReentrant { _claimRewards(_msgSender()); _deposit(); }
9,936,871
./full_match/1/0x0f08eEf2C785AA5e7539684aF04755dEC1347b7c/sources/contracts/admin/GaugeAdder.sol
@inheritdoc IGaugeAdder
function getGaugeTypesCount() external view override returns (uint256) { return _gaugeTypes.length; }
17,154,193
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Hair SVG generator library HairDetail { /// @dev Hair N°1 => Hair Blood function item_1() public pure returns (string memory) { return base(longHair("E31466"), "Hair Blood"); } /// @dev Hair N°2 => Tattoo Blood function item_2() public pure returns (string memory) { return base(tattoo("B50D5E"), "Tattoo Blood"); } /// @dev Hair N°3 => Tattoo Moon function item_3() public pure returns (string memory) { return base(tattoo("000000"), "Tattoo Moon"); } /// @dev Hair N°4 => Tattoo Pure function item_4() public pure returns (string memory) { return base(tattoo("FFEDED"), "Tattoo Pure"); } /// @dev Hair N°5 => Monk Blood function item_5() public pure returns (string memory) { return base(shortHair("B50D5E"), "Monk Blood"); } /// @dev Hair N°6 => Monk Moon function item_6() public pure returns (string memory) { return base(shortHair("001015"), "Monk Moon"); } /// @dev Hair N°7 => Monk Pure function item_7() public pure returns (string memory) { return base(shortHair("FFEDED"), "Monk Pure"); } /// @dev Hair N°8 => Flame Blood function item_8() public pure returns (string memory) { return base(flame("E31466"), "Flame Blood"); } /// @dev Hair N°9 => Flame Moon function item_9() public pure returns (string memory) { return base(flame("2A2C38"), "Flame Moon"); } /// @dev Hair N°10 => Flame Pure function item_10() public pure returns (string memory) { return base(flame("FFDAEA"), "Flame Pure"); } /// @dev Hair N°11 => Top eyes function item_11() public pure returns (string memory) { return base( '<path d="M212.26,68.64S205.37,71,201.72,84c-1.28,4.6-.79,11.21,1.45,18a30.33,30.33,0,0,0,9.55-16.12C213.83,81.08,213.79,75.34,212.26,68.64Z" transform="translate(0 0.5)" /> <path d="M215.93,75.57a28.82,28.82,0,0,1,.15,6.15A36.91,36.91,0,0,1,215,87.81a24.33,24.33,0,0,1-2.36,5.75,23.15,23.15,0,0,1-3.74,4.93c.28-.37.58-.83.88-1.29l.43-.6.35-.63.8-1.31.72-1.34a35.55,35.55,0,0,0,2.16-5.71,36.25,36.25,0,0,0,1.24-6,18.25,18.25,0,0,0,.26-3C215.83,77.61,215.83,76.62,215.93,75.57Z" transform="translate(0 0.5)"/> <path d="M199,85.3c0,1.23-.07,2.45,0,3.69s0,2.39.17,3.64a16.5,16.5,0,0,0,.61,3.63,20,20,0,0,0,1.07,3.53,14.31,14.31,0,0,1-1.45-3.33c-.32-1.2-.48-2.37-.7-3.64,0-1.24-.12-2.4-.07-3.71A32.65,32.65,0,0,1,199,85.3Z" transform="translate(0 0.5)"/> <ellipse cx="211.04" cy="79.75" rx="2.78" ry="0.69" transform="matrix(0.09, -1, 1, 0.09, 111.76, 282.83)" fill="#fff"/>', "Top Eyes" ); } /// @dev Hair N°12 => Middle eyes function item_12() public pure returns (string memory) { return base( '<path d="M213,104.52s-10.09,8.91-23.55-.09C189.55,104.37,200.24,95.64,213,104.52Z" transform="translate(0 0.5)" /> <path d="M211.51,101.33a16.75,16.75,0,0,0-3.14-1.5A23.51,23.51,0,0,0,205,98.9a16.16,16.16,0,0,0-3.53-.27,14.89,14.89,0,0,0-3.43.56c.26,0,.57-.07.88-.1l.41,0,.41,0,.87-.06h.85a21.36,21.36,0,0,1,3.46.35,23,23,0,0,1,3.37.82,12.29,12.29,0,0,1,1.6.58C210.44,100.9,210.94,101.13,211.51,101.33Z" transform="translate(0 0.5)"/> <path d="M199.85,109.75c-.83-.13-1.65-.25-2.48-.43s-1.59-.31-2.42-.55a11,11,0,0,1-2.35-.84,13.15,13.15,0,0,1-2.24-1.14,9.12,9.12,0,0,0,2.06,1.37c.76.36,1.53.6,2.35.91s1.6.36,2.48.48A20.38,20.38,0,0,0,199.85,109.75Z" transform="translate(0 0.5)"/> <ellipse cx="205.62" cy="102.76" rx="0.47" ry="1.89" transform="translate(68.77 287.95) rotate(-80.02)" fill="#fff"/>', "Middle Eyes" ); } /// @dev Hair N°13 => Side eyes function item_13() public pure returns (string memory) { return base( '<g id="Eye"> <path d="M289,147.2s-10.34-8.61-3.5-23.28C285.51,124,295.77,133.19,289,147.2Z" transform="translate(0 0.5)" /> <path d="M281.77,135c0-.83,0-1.67.05-2.51s.06-1.62.17-2.47a10.81,10.81,0,0,1,.47-2.46,13.76,13.76,0,0,1,.78-2.38,9.71,9.71,0,0,0-1,2.24c-.24.81-.36,1.6-.53,2.46s-.12,1.63-.1,2.53A20.5,20.5,0,0,0,281.77,135Z" transform="translate(0 0.5)"/> <ellipse cx="287.94" cy="130.66" rx="0.47" ry="1.89" transform="translate(-26.21 95.24) rotate(-17.88)" fill="#fff"/> </g> <g id="Eye-2" > <path d="M137,147.2s7.8-8.61,2.65-23.28C139.6,124,131.86,133.19,137,147.2Z" transform="translate(0 0.5)" /> <path d="M142.42,135c0-.83,0-1.67,0-2.51s0-1.62-.13-2.47a14.29,14.29,0,0,0-.35-2.46,16.86,16.86,0,0,0-.59-2.38,11,11,0,0,1,.78,2.24c.18.81.28,1.6.4,2.46s.09,1.63.08,2.53A25.66,25.66,0,0,1,142.42,135Z" transform="translate(0 0.5)"/> <ellipse cx="137.95" cy="129.7" rx="1.89" ry="0.36" transform="translate(-25.79 225.29) rotate(-73.38)" fill="#fff"/></g>', "Side Eyes" ); } /// @dev Hair N°14 => Akuma function item_14() public pure returns (string memory) { return base("", "Akuma"); } /// @dev Hair N°15 => Hair Moon function item_15() public pure returns (string memory) { return base(longHair("2A2C38"), "Hair Moon"); } /// @dev Hair N°16 => Hair Pure function item_16() public pure returns (string memory) { return base(longHair("FFDAEA"), "Hair Pure"); } /// @dev Hair N°17 => Tattoo kin function item_17() public pure returns (string memory) { return base( '<g id="Tattoo_kin" display="inline" ><linearGradient id="SVGID_00000011722690206770933430000008680616382255612556_" gradientUnits="userSpaceOnUse" x1="210.6601" y1="-54.3" x2="210.6601" y2="11.1777" gradientTransform="matrix(1 0 0 -1 0 76)"><stop offset="0" style="stop-color:#FFB451" /><stop offset="0.4231" style="stop-color:#F7E394" /><stop offset="1" style="stop-color:#FF9B43" /></linearGradient><path fill="url(#SVGID_00000011722690206770933430000008680616382255612556_)" d="M192.1,67.4c-6.5,21.1,2,49.3,5.5,62.9c0,0,6.9-39.2,34-63.9C220.8,63.6,198.1,64.9,192.1,67.4z" /></g>', "Tattoo kin" ); } function flame(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path display="inline" fill="#', color, '" d="M292.2,168.8c-2.7,2.1-7.7,6-10.4,8.1c3.5-8,7-18.9,7.2-24c-2.4,1.6-6.8,4.7-9.3,4.1 c3.9-12.3,4.2-11.6,4.6-24.2c-2.5,2-8.9,9.3-11.5,11.2c0.5-5.9,0.8-14.3,1.4-20.1c-3.3,3.4-7.6,2.6-12.5,4c-0.5-5,1.3-7,3.5-11.6 c-9.8,4-24.7,6-34.9,8.6c-0.1-2.4-0.6-6.3,0.7-8.1c-10.4,5-26.7,9.3-31.8,12.4c-4.1-2.8-16.9-9.3-19.7-12.9 c-0.1,1.6,0.7,8,0.6,9.6c-5.4-3.8-6.2-3-12-6.8c0.5,2.6,0.3,3.6,0.8,6.2c-7.2-2.8-14.4-5.7-21.6-8.5c1.8,4,3.5,8,5.3,12 c-3.6,0.6-9.9-1.8-12-4.9c-3,7.8-0.1,12.2,0,20.5c-2-2-3.9-6.4-5.4-8.6c0.5,9.6,1,19.1,1.6,28.7c-1.6-0.6-2.7-2-3.1-3.5 c-0.1,5.8,2.6,20.6,4,26.4c-0.8-0.8-5.5-10.9-5.7-12.1c4.3,7.9,4.1,10.5,5.4,26.3c0.9-0.9-5.5-17-8-19.4 c-1.7-15.4-5.3-33.7-9.1-48.8c2,3.6,3.9,7.3,5.8,11c-0.7-13.8-0.7-27.6-0.1-41.4c-0.2,5.9,0.7,11.9,2.6,17.4 c0.5-11.3,2.2-22.4,5.2-33.3c-0.1,4.1,0.4,8.1,1.6,12c2.8-10,6.3-19.8,10.3-29.3c0.8,4.7,1.7,9.4,2.4,14.1 c3.6-9.9,7.9-15.5,14.6-23.7c0.2,4,0.4,7.8,0.7,11.8c6.9-8.9,15-16.8,24.1-23.2c-0.5,4.4-1,8.8-1.6,13.1 c6.1-5.7,11.7-9.7,17.8-15.4c0.3,4.4,1.3,7,1.6,11.5c4-5.4,8.1-9.6,12.1-15c1.4,6.1,2,11.3,2.2,17.6c4.8-4.7,8.1-10,8.4-16.7 c4.2,7.4,7.9,10.6,9.8,18.9c2.5-8.4,4.8-11,4.7-19.8c4.4,10.1,6.8,14.3,9.6,24c0.9-4.6,4.1-11.5,5-16c6.3,6.7,9.1,14.6,12.4,23 c0.7-7.6,5.7-10.6,3.5-17.9c6.5,10.7,4.6,15.2,8.6,27.7c2.9-5.3,4.4-13.3,5.5-19.4c2.7,8,7.7,23.1,9.4,31.5 c0.7-2.7,3.1-3.3,3.5-9.9c2.8,7.7,3.3,8.4,3.5,23.4c1.1-7.4,4.3-3.3,4.5-10.8c3.8,9.6,1.4,14.8,0.4,22.6c-0.1,0.9,4.2-0.4,5.1-1.5 c1-1.3-2.1,12.4-2.8,14.3c-0.5,1.4-1.9,2.7-1.4,8.4c2.2-3.1,2.5-3,4.3-6.4c1.3,11.3-2.3,6-4.7,25.5c1.9-2.5,3.9-1.1,5.6-3.5 c-2.8,7.8-0.4,9.8-6.9,14c-3.3,2.1-11.2,10.3-14.2,13.5c1.6-3.3-2.9,9.8-8.2,18.8C284.5,199.5,289.7,170.7,292.2,168.8z"/>' ) ); } function tattoo(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path d="M193.2,67.36c-6.5,21.1,3,50.54,6.48,64.14,0,0,5.91-44.63,33.11-64.86C222,63.84,201.2,64.36,193.2,67.36Z" fill="#', color, '" transform="translate(-0.1)"/>' ) ); } function longHair(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<g ><polygon fill="#', color, '" points="188.1,115.5 198.2,119 211.1,115.2 197.7,104.1 "/><polygon opacity="0.5" enable-background="new " points="188.3,115.6 198.2,119 211.6,115.1 197.6,104.5 "/><path fill="#', color, '" stroke="#000000" stroke-width="2" stroke-miterlimit="10" d="M273.7,200.6c4.2-5.9,10.1-12.8,10.5-18.3c1.1,3.2,2,11.7,1.5,15.8c0,0,5.7-10.8,10.6-15.6c6.4-6.3,13.9-10.2,17.2-14.4c2.3,6.4,1.4,15.3-4.7,28.1c0,0,0.4,9.2-0.7,15.3c3.3-5.9,12.8-36.2,8.5-61.6c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2c-0.1-0.1-15.1-12.2-34.2-7.1c0,0-15.1-13.6-42.6-12.3l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9c0,0-2.9,15.4-1.1,29.6c0,0,7.2-26.8,17.3-40.1c0,0,0.8,0.1,17.6-7.6c6.3,3.1,8,1.4,17.9,7.7c4.1,5.3,13.8,31.9,15.6,41.5c3.4-7.3,5.6-19,5.2-29.5c2.7,3.7,8.9,19.9,9.6,34.3c4.3-6,6.4-27.8,5.9-29c0,1.2,0.2,14.8,0.3,14.3c0,0,12.1,19.9,14.9,19.7c0-0.8-1.7-12.9-1.7-12.8c1.3,5.8,2.8,23.3,3.1,27.1l5-9.5C274.6,176.2,275.4,194.5,273.7,200.6z"/><g><path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M295.2,182.2"/><path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286.6,200.9"/><path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" d="M133.1,181.3c0,0-1.3-11.3,0.3-16.9"/><path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" d="M142.1,160.9c0,0-1-6.5,1.6-20.4"/></g></g><g id="Shadow"><path opacity="0.2" enable-background="new " d="M180.5,119.1c0,0-15.9,23.7-16.9,25.6s0,12.4,0.3,12.8S165.7,142.5,180.5,119.1z"/><path opacity="0.2" enable-background="new " d="M164.5,128.9c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L164.5,128.9z"/><path opacity="0.16" enable-background="new " d="M253.2,146.8c0.8,4.4,8.1,12.1,13.1,11.7l1.6,11c0,0-5.2-3.9-14.7-19.9V146.8z"/><path opacity="0.16" enable-background="new " d="M237.5,130.3c0,0,4.4,3,13.9,21.7c0,0-4.3,12-4.6,12.4C246.5,164.8,248.4,153.7,237.5,130.3z"/><path opacity="0.17" enable-background="new " d="M220.9,127.6c0,0,5.2,4,14.4,23c0,0-1.2,4.6-3.1,8.9C227.6,143.3,227,140.8,220.9,127.6z"/><path opacity="0.2" enable-background="new " d="M272,143.7c-2.4,8.1-3.6,13.8-4.9,17.9c0,0,1.3,12.8,2.1,22.2c4.7-8.4,4.7-8.4,5.4-9c0.2,0.6,3.1,11.9-1.2,26.6c5.1-6.7,10.4-14.9,11-21.3c1.1,3.7,1.7,15,1.2,19.1c0,0,7.1-7.4,12.3-11.3c0,0,8.7-3.5,12.5-7.2c0,0,2.2,1.4-1.2,11.6l3.7-8c0,0-2.7,19.9-3.4,22.5c0,0,9.8-33.3,7.2-58c0,0,4.7,8.3,4.9,17.1c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,1.3,10.1,0.4,13.6c0,0-7.3-10.3-10.5-12.5c0,0,1.1,30.2-1.7,35.3c0,0-6.1-17-10.7-20.8c0,0-2.4,20.9-5.6,28.1C283.6,174.1,280.4,157.8,272,143.7z"/><path opacity="0.14" enable-background="new " d="M198.1,106.1c-0.9-3.9,3.2-35.1,34.7-36C227.5,69.4,198.8,90.7,198.1,106.1z"/></g><g id="Light" opacity="0.64"> <path d="M128,115.68s9.5-20.6,23.5-27.7A231.28,231.28,0,0,0,128,115.68Z" transform="translate(-0.48 0.37)" fill="#fff"/> <path d="M302.32,118.62s-12.77-26.38-29.75-35A151.52,151.52,0,0,1,302.32,118.62Z" transform="translate(-0.48 0.37)" fill="#fff"/> <path d="M251.35,127.49s-9.25-18.73-11.63-21.13,5,1.76,12.17,20.33" transform="translate(-0.48 0.37)" fill="#fff"/> <path d="M168.21,103.68s-10.66,10.79-16,23.94C157.36,118,168.21,103.68,168.21,103.68Z" transform="translate(-0.48 0.37)" fill="#fff"/> <path d="M170,126.1s7.5-21.3,8.4-22.5-12.6,11.4-13.1,18c0,0,9-12.8,9.5-13.5S168.8,121.8,170,126.1Z" transform="translate(-0.48 0.37)" fill="#fff"/> <path d="M233.09,127.55s-7.5-21.3-8.4-22.5,12.6,11.4,13.1,18c0,0-9-12.8-9.5-13.5S234.29,123.25,233.09,127.55Z" transform="translate(-0.48 0.37)" fill="#fff"/> </g>' ) ); } function spike(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path display="inline" fill="#', color, '" stroke="#', color, '" stroke-miterlimit="10" d="M197.7,120.1c0,0-26.4-38.7-18-80.2c0,0,0.6,18.5,10.4,25.8c0,0-7.5-13.9-0.3-34.5c0,0,2.3,16.4,9.3,24.1c0,0-2.3-19.1,1.9-30.5c0,0,8.4,23.9,12.1,27.1c0,0-2.8-16.2,4.8-28.6c0,0,2.2,17.1,8.5,26.2c0,0-2.3-11.5,3.4-19.6c0,0,1,25.8,5.7,30.3c0,0-2.3-12.4,1.8-20.7c0,0,3.6,24.4,5.9,29c-7.9-2.6-14.6-2.1-22.2-1.9C221.3,67,199.4,74.8,197.7,120.1z"/>' ) ); } function shortHair(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path display="inline" fill="#', color, '" d="M288.2,192.7c0,0,0.1-18.3-2.9-21.5c-3.1-3-7.4-9.2-7.4-9.2s0.3-22.2-3.2-29.6c-3.6-7.4-4.6-19.5-36.1-18.7c-30.7,0.7-41.1,5.8-41.1,5.8s-13.1-7.7-41.9-4c-19.6,5.2-20.3,42.6-20.3,42.6s-1.3,9.2-1.9,14.7c-0.6,5.6-0.3,8.5-0.3,8.5c-0.9,11.8-27.4-116.1,81.3-119.6c110.4,6.8,89.8,101.8,86.7,115.3C295.8,180.8,294.7,183.1,288.2,192.7z" />', '<g id="Shadow" display="inline" > <path opacity="7.000000e-02" enable-background="new " d="M277,141.5c0,0,0.9,3.6,0.9,20.6c0,0,6.6,7.9,8.6,11.7c2,3.6,2.6,18.8,2.6,18.8l5.4-9.2c0,0,1.5-1.8,5.7-4c0,0,7-15.6,3.4-46.3C303.7,133.1,295.1,139.9,277,141.5z" /> <path opacity="7.000000e-02" enable-background="new " d="M132.9,182.7c0,0,0.4-11.3,2.3-24.4c0,0,1.9-15.1,3.4-21.9c-1.9,0-6.9,0-8.5-1.1C130,135.3,128.7,177.5,132.9,182.7z" /> </g>' ) ); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Hair Blood"; } else if (id == 2) { name = "Tattoo Blood"; } else if (id == 3) { name = "Tattoo Moon"; } else if (id == 4) { name = "Tattoo Pure"; } else if (id == 5) { name = "Monk Blood"; } else if (id == 6) { name = "Monk Moon"; } else if (id == 7) { name = "Monk Pure"; } else if (id == 8) { name = "Flame Blood"; } else if (id == 9) { name = "Flame Moon"; } else if (id == 10) { name = "Flame Pure"; } else if (id == 11) { name = "Top eyes"; } else if (id == 12) { name = "Middle eyes"; } else if (id == 13) { name = "Side eyes"; } else if (id == 14) { name = "Akuma"; } else if (id == 15) { name = "Hair Moon"; } else if (id == 16) { name = "Hair Pure"; } else if (id == 17) { name = "Tatoo Kin"; } } /// @dev The base SVG for the body function base(string memory children, string memory name) private pure returns (string memory) { return string(abi.encodePacked('<g id="hair"><g id="', name, '">', children, "</g></g>")); } }
Hair N°8 => Flame Blood
function item_8() public pure returns (string memory) { return base(flame("E31466"), "Flame Blood"); }
12,688,927
./full_match/43114/0x42C03f6d6c00f0D5603080a3475903195e9F6CEc/sources/BankerJoeFeeCollector.sol
Updates the treasury address used to recover lost funds. This is a privileged function. _newTreasury The new treasury address./
function setTreasury(address _newTreasury) external onlyOwner delayed(this.setTreasury.selector, keccak256(abi.encode(_newTreasury))) { require(_newTreasury != address(0), "invalid address"); address _oldTreasury = treasury; treasury = _newTreasury; emit ChangeTreasury(_oldTreasury, _newTreasury); }
4,536,417
pragma solidity ^0.5.0; /** * @title VotingContract * @dev Implements a voting contract will be used by judges serving as oracles in a market such as https://www.floater.market */ contract VotingContract { // a vote window, which is a period in days which should be set in the future uint private votingStartDate; uint private votingEndDate; // a variable that shows the voting status, by default it shows the voting hasn't began string public votingStatus = "VOTENOTREADY"; // the details whats being voted for string public voteDetailsName; // and the description string public voteDetailsDescription; // represents a single vote struct Vote { string name; // i.e. "TRUE" , "UNDECIDED" or "FALSE" string _event; // the event being voted for } // a judge in the voting process struct Judge { string name; string description; address judgeAddress; } // the votes mapping (address => Vote) public votes; // the judges mapping (address => Judge) public judges; // the various events being voted for and the final vote result mapping(string => string[]) events; // the owner of the contract address owner; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier onlyOwnerAndJudge() { require(msg.sender == owner && judges[msg.sender].judgeAddress == msg.sender && judges[msg.sender].judgeAddress != address(0), "Only the owner or judge can edit an exisiting judge"); _; } modifier votePeriodMustBeSet() { // set a valid voting period require( votingStartDate > 0 && votingEndDate > 0, "A valid vote window must be set"); _; } modifier votingShouldNotHaveStarted() { // no changes should be allowed when voting has started require(now < votingStartDate , "Can't modify variable(s) because voting has already started"); _; } modifier futureVotingDate(uint _votingDate) { // make sure any of the voting date set is in the future require(_votingDate > now, "voting date must be in the future"); _; } modifier validVotingPeriod(uint _votingStartDate, uint _votingEndDate) { // make sure any of the voting date set is in the future require(_votingEndDate > _votingStartDate, "Voting end date should be greater than the voting start date"); _; } modifier votingEligible() { // make sure the voting period is in range and the voter is already added as a judge require(votingStartDate > 0 && votingEndDate > 0 && now >= votingStartDate && now <= votingEndDate && judges[msg.sender].judgeAddress == msg.sender && judges[msg.sender].judgeAddress != address(0), "Voting not eligible! make sure you are in the voting period, the voting period is valid and are added as a judge"); _; } modifier validVote(string memory _vote) { // make sure a vote is valid require(compareStrings(_vote, "TRUE") || compareStrings(_vote, "FALSE") || compareStrings(_vote, "UNDECIDED") , "Please cast a valid vote of either TRUE, FALSE or UNDECIDED"); _; } // set the contract owner, the name of whats being voted for and the description constructor(string memory _voteDetailsName, string memory _voteDetailsDescription) public { owner = msg.sender; voteDetailsName = _voteDetailsName; voteDetailsDescription = _voteDetailsDescription; } // function to set a voting period before the voting starts by setting the start and end dates function setVotingPeriodByDates(uint _startDate, uint _endDate) external futureVotingDate(_startDate) futureVotingDate(_endDate) validVotingPeriod(_startDate, _endDate) votingShouldNotHaveStarted() onlyOwner() { votingStartDate = _startDate; votingEndDate = _endDate; } // function to set a voting period before the voting starts function setVotingPeriod(uint _daysToVoteStart, uint _votingDurationDays) external votingShouldNotHaveStarted() onlyOwner() { votingStartDate = now + _daysToVoteStart * 1 days; votingEndDate = now + _daysToVoteStart * 1 days + _votingDurationDays * 1 days; } // function to reset a voting period before the voting starts function resetVotingPeriod() external votingShouldNotHaveStarted() onlyOwner() { votingStartDate = 0; votingEndDate = 0; } // function to add a judge before voting starts function addJudge(string memory _name, string memory desc, address judgeAddress) public votingShouldNotHaveStarted() onlyOwner() { judges[judgeAddress] = Judge(_name, desc, judgeAddress); } // function to edit a judge before voting starts function editJudge(string memory _name, string memory desc, address judgeAddress) public votingShouldNotHaveStarted() onlyOwnerAndJudge() { judges[judgeAddress] = Judge(_name, desc, judgeAddress); } // function to remove a judge before voting starts function removeJudge(address judgeAddress) public votingShouldNotHaveStarted() onlyOwner() { delete judges[judgeAddress]; } // function to modify whats being voted on and the description function changeVotingDetails(string memory _voteDetailsName, string memory _voteDetailsDescription) public votingShouldNotHaveStarted() onlyOwner() { voteDetailsName = _voteDetailsName; voteDetailsDescription = _voteDetailsDescription; } function voteForEvent(string memory _theEvent, string memory _vote ) public votingEligible() validVote(_vote) { // flag the voting process has having been started votingStatus = "VOTEINPROGRESS"; // save the vote by a particular judge votes[msg.sender] = Vote(_vote, _theEvent); // push the vote for the event in the event array events[_theEvent].push(_vote); } function getResultFromOracle(string memory _theEvent, uint _dataIndex) public view returns (string memory) { string memory votingResult = ""; // voting has not yet started if (now < votingStartDate ) { votingResult = votingStatus; } // if in voting period, return the voting status if (now >= votingStartDate && now <= votingEndDate ) { votingResult = votingStatus; } // voting period has ended, then aggregate all the results if (now > votingEndDate) { uint trueCount = 0; uint falseCount = 0; uint undecidedCount = 0; for (uint i = 0; i < events[_theEvent].length; i++) { string memory vote = events[_theEvent][i]; if (compareStrings(vote,"TRUE")) { trueCount = trueCount + 1; } if (compareStrings(vote,"FALSE")) { falseCount = falseCount + 1; } if (compareStrings(vote,"UNDECIDED")) { undecidedCount = undecidedCount + 1; } } // aggregate the results if (trueCount > falseCount && trueCount > undecidedCount) { votingResult = "TRUE"; } else if (falseCount > trueCount && falseCount > undecidedCount) { votingResult = "FALSE"; } else if (undecidedCount > trueCount && undecidedCount > falseCount) { votingResult = "UNDECIDED"; } else { votingResult = events[_theEvent][_dataIndex]; } } return votingResult; } // function to get the time till vote function getTimeTilVote() external view returns (uint){ uint timeTilVote = 0; if (votingStartDate > now) { timeTilVote = votingStartDate - now; } return timeTilVote; } // helper function to compare strings function compareStrings (string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) ); } }
function to remove a judge before voting starts
function removeJudge(address judgeAddress) public votingShouldNotHaveStarted() onlyOwner() { delete judges[judgeAddress]; }
15,808,778
./full_match/1/0x59213AE27c9F6014a788358f623a0E626140f0cd/sources/contracts/PPPCollection.sol
OpenZeppelin hook that is called before any token transfer, including minting and burning
function _beforeTokenTransfer(address from, address to, uint256 id, uint256 quantity) internal virtual override { if (from != address(0) && from != msg.sender && !operatorAllowed(msg.sender)) { revert OperatorNotAllowed(msg.sender); } super._beforeTokenTransfer(from, to, id, quantity); }
8,466,526
./full_match/1/0xCFc60d34949A7DBdf91ba6D5613b26d6Ff0AD504/sources/src/core/Pomace.sol
burn array of option tokens and get out cash value at expiry _account who to settle for _tokenIds array of tokenIds to burn _amounts array of amounts to burn/
function batchSettleOptions(address _account, uint256[] memory _tokenIds, uint256[] memory _amounts) external nonReentrant { if (_tokenIds.length != _amounts.length) revert PM_WrongArgumentLength(); if (_tokenIds.length == 0) return; optionToken.batchBurnPomaceOnly(_account, _tokenIds, _amounts); for (uint256 i; i < _tokenIds.length;) { settleOption(_account, _tokenIds[i], _amounts[i]); unchecked { ++i; } } }
4,921,121
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/governance/utils/Votes.sol
Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to` should be zero. Total supply of voting units will be adjusted with mints and burns./
function _transferVotingUnits(address from, address to, uint256 amount) internal virtual { if (from == address(0)) { _push(_totalCheckpoints, _add, SafeCast.toUint208(amount)); } if (to == address(0)) { _push(_totalCheckpoints, _subtract, SafeCast.toUint208(amount)); } _moveDelegateVotes(delegates(from), delegates(to), amount); }
8,083,912
pragma solidity ^0.4.17; contract Mortgage{ /* This is the constructor which will deploy the contract on the blockchain. We will initialize with the loan status as 'Initiated' and for test purposes we will initialize the loan applicant's balance to 1000000. Note since solidity does not support float or double at this point, we will store the actual value multipled by 100 in the contract, and will be divide the value retrieved from the contract by 100, when we have to represent the balance in the UI */ function Mortgage() { loanApplicant = msg.sender; loan.status = STATUS_INITIATED; balances[msg.sender] = 100000000; } /* address of the loan applicant */ address loanApplicant; // Events - publicize actions to external listeners event LienReleased(address _owner); event LienTrasferred (address _owner); event LoanStatus (int _status); int constant STATUS_INITIATED = 0; int constant STATUS_SUBMITTED = 1; int constant STATUS_APPROVED = 2; int constant STATUS_REJECTED = 3; /* struct datatype to store the property details */ struct Property { bytes32 addressOfProperty; uint32 purchasePrice; address owner; } /* struct datatype to store the loan terms */ struct LoanTerms{ uint32 term; uint32 interest; uint32 loanAmount; uint32 annualTax; uint32 annualInsurance; } /* struct datatype to store the monthly payment structure */ struct MonthlyPayment{ uint32 pi; uint32 tax; uint32 insurance; } /* struct datatype to store the details of the loan contract */ struct Loan { LoanTerms loanTerms; Property property; MonthlyPayment monthlyPayment; ActorAccounts actorAccounts; int status; // values: SUBMITTED, APPROVED, REJECTED } struct ActorAccounts { address mortgageHolder; address insurer; address irs; } Loan loan; LoanTerms loanTerms; Property property; MonthlyPayment monthlyPayment; ActorAccounts actorAccounts; /* mapping is equivalent to an associate array or hash Maps addresses of the actors in the mortgage contract with their balances */ mapping (address => uint256) public balances; /* This means that if the mortgage holder calls this function, the function is executed and otherwise, an exception is thrown */ modifier bankOnly { if(msg.sender != loan.actorAccounts.mortgageHolder) { throw; } _; } /* deposit into actor accounts and will return the balance of the user after the deposit is made */ function deposit(address receiver, uint amount) returns(uint256) { if (balances[msg.sender] < amount) return; balances[msg.sender] -= amount; balances[receiver] += amount; checkMortgagePayoff(); return balances[receiver]; } /* 'constant' prevents function from editing state variables; */ function getBalance(address receiver) constant returns(uint256){ return balances[receiver]; } /* check if mortgage payment if complete, if complete, then release the property lien to the homeowner */ function checkMortgagePayoff(){ if(balances[loan.actorAccounts.mortgageHolder] ==loan.monthlyPayment.pi*12*loan.loanTerms.term && balances[loan.actorAccounts.insurer] ==loan.monthlyPayment.tax*12*loan.loanTerms.term && balances[loan.actorAccounts.irs] ==loan.monthlyPayment.insurance*12*loan.loanTerms.term ){ loan.property.owner = loanApplicant; LienReleased(loan.property.owner); } } /* Add loan details into the contract */ function submitLoan( bytes32 _addressOfProperty, uint32 _purchasePrice, uint32 _term, uint32 _interest, uint32 _loanAmount, uint32 _annualTax, uint32 _annualInsurance, uint32 _monthlyPi, uint32 _monthlyTax, uint32 _monthlyInsurance, address _mortgageHolder, address _insurer, address _irs ){ loan.property.addressOfProperty = _addressOfProperty; loan.property.purchasePrice = _purchasePrice; loan.loanTerms.term=_term; loan.loanTerms.interest=_interest; loan.loanTerms.loanAmount=_loanAmount; loan.loanTerms.annualTax=_annualTax; loan.loanTerms.annualInsurance=_annualInsurance; loan.monthlyPayment.pi=_monthlyPi; loan.monthlyPayment.tax=_monthlyTax; loan.monthlyPayment.insurance=_monthlyInsurance; loan.actorAccounts.mortgageHolder = _mortgageHolder; loan.actorAccounts.insurer = _insurer; loan.actorAccounts.irs = _irs; loan.status = STATUS_SUBMITTED; } /* Gets loan details from the contract */ function getLoanData() constant returns ( bytes32 _addressOfProperty, uint32 _purchasePrice, uint32 _term, uint32 _interest, uint32 _loanAmount, uint32 _annualTax, uint32 _annualInsurance, int _status, uint32 _monthlyPi, uint32 _monthlyTax, uint32 _monthlyInsurance) { _addressOfProperty = loan.property.addressOfProperty; _purchasePrice=loan.property.purchasePrice; _term=loan.loanTerms.term; _interest=loan.loanTerms.interest; _loanAmount=loan.loanTerms.loanAmount; _annualTax=loan.loanTerms.annualTax; _annualInsurance=loan.loanTerms.annualInsurance; _monthlyPi=loan.monthlyPayment.pi; _monthlyTax=loan.monthlyPayment.tax; _monthlyInsurance=loan.monthlyPayment.insurance; _status = loan.status; } /* Approve or reject loan */ function approveRejectLoan(int _status) bankOnly { //if(msg.sender == loanApplicant) throw; loan.status = _status ; /* if status is approved, transfer the lien of the property to the mortgage holder */ if(_status == STATUS_APPROVED) { loan.property.owner = msg.sender; LienTrasferred(loan.property.owner); } LoanStatus(loan.status); } }
Approve or reject loan /if(msg.sender == loanApplicant) throw; if status is approved, transfer the lien of the property
function approveRejectLoan(int _status) bankOnly { loan.status = _status ; to the mortgage holder */ if(_status == STATUS_APPROVED) { loan.property.owner = msg.sender; LienTrasferred(loan.property.owner); } LoanStatus(loan.status); }
6,455,779
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./GMON.sol"; import "./GameCollectionV2.sol"; import "./GameFactory.sol"; struct GameGuildInfo { uint256 id; uint256 land; string name; string symbol; string logo; } struct GuildRequest { bytes32 referrer; uint256 monsterId; uint256 timestamp; } contract GameGuild is Ownable { using SafeMath for uint256; address public Game_FACTORY; address public GUILD_TOKEN_ADDRESS; address public founder; address[] private _members; mapping(bytes32 => address) private _referrers; mapping(uint256 => address) private _genesisMonstersOwners; mapping(uint256 => address) private _z1MonsterOwners; mapping(uint256 => address) private _z1MonsterPlayers; address[] private _joinRequesters; mapping(address => GuildRequest) private _joinRequests; GameGuildInfo private _info; modifier onlyMember() { for (uint256 i = 0; i < _members.length; i++) { if (_members[i] == msg.sender) { _; return; } } revert("You needs be member of guild."); } constructor() { Game_FACTORY = msg.sender; } function initialize( address founder_, GameGuildInfo memory info, uint256[] calldata monsters ) public returns (bytes32 defaultReferrer) { require(msg.sender == Game_FACTORY, "Game guild: FORBIDDEN"); // sufficient check founder = founder_; _info = info; for (uint256 idx = 0; idx < monsters.length; idx++) { _genesisMonstersOwners[monsters[idx]] = founder_; } _members.push(founder_); defaultReferrer = generateReferrCode(founder_); _referrers[defaultReferrer] = founder_; } function getInfo() external view returns ( uint256, uint256, string memory, string memory, string memory ) { return (_info.id, _info.land, _info.name, _info.symbol, _info.logo); } function requestDetails(uint256 monsterId) external view returns (GuildRequest memory) { GuildRequest memory request; for (uint256 i = 0; i < _joinRequesters.length; i++) { if (_joinRequests[_joinRequesters[i]].monsterId == monsterId) { return _joinRequests[_joinRequesters[i]]; } } return request; } function requestJoin( address requester, bytes32 referrer, uint256 monsterId ) public { require(msg.sender == Game_FACTORY, "Game guild: FORBIDDEN"); // sufficient check require(_joinRequests[requester].referrer == 0, "Already requested."); // Transfer GMON token as join fee address gmon_address = GameFactory(Game_FACTORY).GMON_ADDRESS(); address treasury_address = GameFactory(Game_FACTORY).TREASURY_ADDRESS(); uint256 gmon_amount = GameFactory(Game_FACTORY) .JOIN_GMON_AMOUNT(); GMON(gmon_address).transferFrom(requester, treasury_address, gmon_amount); // Transfer guild token as join fee // GMON_GUILD(GUILD_TOKEN_ADDRESS).transferFrom(requester, address(this), JOIN_GTOKEN_AMOUNT); _joinRequesters.push(requester); _joinRequests[requester] = GuildRequest( referrer, monsterId, block.timestamp ); } function acceptJoin(address requester, uint256 monsterId) public onlyMember returns (bytes32 referrer) { require( _z1MonsterOwners[monsterId] == msg.sender, "You need to own monster." ); // z1 monster owner check require( _z1MonsterPlayers[monsterId] == msg.sender, "You already assigned that monster to other member." ); // z1 monster player check if (_joinRequests[requester].monsterId > 0) { require( monsterId == _joinRequests[requester].monsterId, "Your monster not matched with requested." ); // specify monster id check } // Assign monster to requester _z1MonsterPlayers[monsterId] = requester; referrer = generateReferrCode(requester); _referrers[referrer] = requester; _members.push(requester); } function revokeJoin(address requester) public { require(msg.sender == Game_FACTORY, "Game guild: FORBIDDEN"); // sufficient check require( _joinRequests[requester].referrer > 0, "You have no join request." ); // Revert guild token // GMON_GUILD(GUILD_TOKEN_ADDRESS).transfer(requester, JOIN_GTOKEN_AMOUNT); // Set empty value for request _joinRequests[requester] = GuildRequest(0, 0, 0); } function claimJoinFee(address requester) public { require(msg.sender == Game_FACTORY, "Game guild: FORBIDDEN"); // sufficient check require( _joinRequests[requester].referrer > 0, "You have no join request." ); uint256 expired_timestamp = GameFactory(Game_FACTORY) .JOIN_EXPIRED_TIMESTAMP(); // Check expired require( _joinRequests[requester].timestamp + expired_timestamp < block.timestamp, "Your request not expired yet." ); // Revert guild token // uint256 gtoken_amount = GameFactory(Game_FACTORY).JOIN_GTOKEN_AMOUNT(); // GMON_GUILD(GUILD_TOKEN_ADDRESS).transfer(requester, gtoken_amount); // Set empty value for request _joinRequests[requester] = GuildRequest(0, 0, 0); } function addMonsters(uint256[] memory monsterIds) external onlyMember { address gmonc_z1_address = GameFactory(Game_FACTORY) .GMONC_Z1_ADDRESS(); for (uint256 i = 0; i < monsterIds.length; i++) { uint256 monsterId = monsterIds[i]; require( GameZ1(gmonc_z1_address).ownerOf(monsterId) == msg.sender, "You not own that monster." ); _z1MonsterOwners[monsterId] = msg.sender; _z1MonsterPlayers[monsterId] = msg.sender; } // Reward guild token // GMON_GUILD(GUILD_TOKEN_ADDRESS).transfer(requester, reward_amount); } // Generate referrer code with address and guild id function generateReferrCode(address user) private view returns (bytes32 referrerCode) { referrerCode = keccak256( abi.encodePacked(user, _info.name, block.number) ); } }
Transfer GMON token as join fee Transfer guild token as join fee GMON_GUILD(GUILD_TOKEN_ADDRESS).transferFrom(requester, address(this), JOIN_GTOKEN_AMOUNT);
function requestJoin( address requester, bytes32 referrer, uint256 monsterId ) public { require(_joinRequests[requester].referrer == 0, "Already requested."); address gmon_address = GameFactory(Game_FACTORY).GMON_ADDRESS(); address treasury_address = GameFactory(Game_FACTORY).TREASURY_ADDRESS(); uint256 gmon_amount = GameFactory(Game_FACTORY) .JOIN_GMON_AMOUNT(); GMON(gmon_address).transferFrom(requester, treasury_address, gmon_amount); _joinRequesters.push(requester); _joinRequests[requester] = GuildRequest( referrer, monsterId, block.timestamp ); }
2,549,105
./full_match/1/0x6928b8F5DC33A53C7001Aed4fA13e52Be284D331/sources/contracts/Database.sol
Returns amount of audits completed at each level for `auditorAdderss_` auditorAddress_ Address of auditor return levelsCompleted_ Array of levels of audits completed for `auditorAddress_`
function levelsCompleted(address auditorAddress_) external view returns (uint256[4] memory levelsCompleted_) { return (_levelsCompleted[auditorAddress_]); }
8,466,813
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; import "./internalModule.sol"; /** * @title BiFi's Reward Distribution View Contract * @notice Implements the view functions for support front-end * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract viewModule is internalModule { function marketInformation(uint256 _fromBlockNumber, uint256 _toBlockNumber) external view returns ( uint256 rewardStartBlockNumber, uint256 distributedAmount, uint256 totalDeposit, uint256 poolRate ) { if(rewardPerBlock == 0) rewardStartBlockNumber = registeredPoints[0].blockNumber; else rewardStartBlockNumber = registeredPoints[0].blockNumber; distributedAmount = _redeemAllView(address(0)); totalDeposit = totalDeposited; poolRate = getPoolRate(address(0), _fromBlockNumber, _toBlockNumber); return ( rewardStartBlockNumber, distributedAmount, totalDeposit, poolRate ); } function userInformation(address userAddr, uint256 _fromBlockNumber, uint256 _toBlockNumber) external view returns ( uint256 stakedTokenAmount, uint256 rewardStartBlockNumber, uint256 claimStartBlockNumber, uint256 earnedTokenAmount, uint256 poolRate ) { Account memory user = accounts[userAddr]; stakedTokenAmount = user.deposited; if(rewardPerBlock == 0) rewardStartBlockNumber = registeredPoints[0].blockNumber; else rewardStartBlockNumber = registeredPoints[0].blockNumber; earnedTokenAmount = _redeemAllView(userAddr); poolRate = getPoolRate(userAddr, _fromBlockNumber, _toBlockNumber); return (stakedTokenAmount, rewardStartBlockNumber, claimStartBlockNumber, earnedTokenAmount, poolRate); } function modelInfo() external view returns (uint256, uint256, uint256, uint256, uint256) { return (rewardPerBlock, decrementUnitPerBlock, rewardLane, lastBlockNum, totalDeposited); } function getParams() external view returns (uint256, uint256, uint256, uint256) { return (rewardPerBlock, rewardLane, lastBlockNum, totalDeposited); } function getRegisteredPointLength() external view returns (uint256) { return registeredPoints.length; } function getRegisteredPoint(uint256 index) external view returns (uint256, uint256, uint256) { RewardVelocityPoint memory point = registeredPoints[index]; return (point.blockNumber, point.rewardPerBlock, point.decrementUnitPerBlock); } function userInfo(address userAddr) external view returns (uint256, uint256, uint256) { Account memory user = accounts[userAddr]; uint256 earnedRewardAmount = _redeemAllView(userAddr); return (user.deposited, user.pointOnLane, earnedRewardAmount); } function distributionInfo() external view returns (uint256, uint256, uint256) { uint256 totalDistributedRewardAmount_now = _distributedRewardAmountView(); return (rewardPerBlock, decrementUnitPerBlock, totalDistributedRewardAmount_now); } function _distributedRewardAmountView() internal view returns (uint256) { return _redeemAllView( address(0) ); } function _redeemAllView(address userAddr) internal view returns (uint256) { Account memory user; uint256 newRewardLane; if( userAddr != address(0) ) { user = accounts[userAddr]; newRewardLane = _updateRewardLaneView(lastBlockNum); } else { user = Account(totalDeposited, 0, 0); newRewardLane = _updateRewardLaneView(0); } uint256 distance = safeSub(newRewardLane, user.pointOnLane); uint256 rewardAmount = expMul(user.deposited, distance); return safeAdd(user.rewardAmount, rewardAmount); } function _updateRewardLaneView(uint256 fromBlockNumber) internal view returns (uint256) { /// @dev Set up memory variables used for calculation temporarily. UpdateRewardLaneModel memory vars; vars.len = registeredPoints.length; vars.memTotalDeposit = totalDeposited; if(fromBlockNumber == 0){ vars.tmpPassedPoint = vars.memPassedPoint = 0; vars.memThisBlockNum = block.number; vars.tmpLastBlockNum = vars.memLastBlockNum = 0; vars.tmpRewardLane = vars.memRewardLane = 0; vars.tmpRewardPerBlock = vars.memRewardPerBlock = 0; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock = 0; } else { vars.tmpPassedPoint = vars.memPassedPoint = passedPoint; vars.memThisBlockNum = block.number; vars.tmpLastBlockNum = vars.memLastBlockNum = fromBlockNumber; vars.tmpRewardLane = vars.memRewardLane = rewardLane; vars.tmpRewardPerBlock = vars.memRewardPerBlock = rewardPerBlock; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock = decrementUnitPerBlock; } for(uint256 i=vars.memPassedPoint; i<vars.len; i++) { RewardVelocityPoint memory point = registeredPoints[i]; /** * @dev Check whether this reward velocity point is valid and has not applied yet. */ if(vars.tmpLastBlockNum < point.blockNumber && point.blockNumber <= vars.memThisBlockNum) { vars.tmpPassedPoint = i+1; /// @dev Update the reward lane with the tmp variables vars.tmpBlockDelta = safeSub(point.blockNumber, vars.tmpLastBlockNum); (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); /// @dev Update the tmp variables with this reward velocity point. vars.tmpLastBlockNum = point.blockNumber; vars.tmpRewardPerBlock = point.rewardPerBlock; vars.tmpDecrementUnitPerBlock = point.decrementUnitPerBlock; /** * @dev Notify the update of the parameters (by passing the reward velocity points) */ } else { /// @dev sorted array, exit eariler without accessing future points. break; } } /** * @dev Update the reward lane for the remained period between the latest velocity point and this moment (block) */ if(vars.memThisBlockNum > vars.tmpLastBlockNum) { vars.tmpBlockDelta = safeSub(vars.memThisBlockNum, vars.tmpLastBlockNum); vars.tmpLastBlockNum = vars.memThisBlockNum; (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); } return vars.tmpRewardLane; } /** * @notice Get The rewardPerBlock of user in suggested period(see params) * @param userAddr The Address of user, 0 for total * @param fromBlockNumber calculation start block number * @param toBlockNumber calculation end block number * @notice this function calculate based on current contract state */ function getPoolRate(address userAddr, uint256 fromBlockNumber, uint256 toBlockNumber) internal view returns (uint256) { UpdateRewardLaneModel memory vars; vars.len = registeredPoints.length; vars.memTotalDeposit = totalDeposited; vars.tmpLastBlockNum = vars.memLastBlockNum = fromBlockNumber; (vars.memPassedPoint, vars.memRewardPerBlock, vars.memDecrementUnitPerBlock) = getParamsByBlockNumber(fromBlockNumber); vars.tmpPassedPoint = vars.memPassedPoint; vars.tmpRewardPerBlock = vars.memRewardPerBlock; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock; vars.memThisBlockNum = toBlockNumber; vars.tmpRewardLane = vars.memRewardLane = 0; for(uint256 i=vars.memPassedPoint; i<vars.len; i++) { RewardVelocityPoint memory point = registeredPoints[i]; if(vars.tmpLastBlockNum < point.blockNumber && point.blockNumber <= vars.memThisBlockNum) { vars.tmpPassedPoint = i+1; vars.tmpBlockDelta = safeSub(point.blockNumber, vars.tmpLastBlockNum); (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); vars.tmpLastBlockNum = point.blockNumber; vars.tmpRewardPerBlock = point.rewardPerBlock; vars.tmpDecrementUnitPerBlock = point.decrementUnitPerBlock; } else { break; } } if(vars.memThisBlockNum > vars.tmpLastBlockNum) { vars.tmpBlockDelta = safeSub(vars.memThisBlockNum, vars.tmpLastBlockNum); vars.tmpLastBlockNum = vars.memThisBlockNum; (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); } Account memory user; if( userAddr != address(0) ) user = accounts[userAddr]; else user = Account(vars.memTotalDeposit, 0, 0); return safeDiv(expMul(user.deposited, vars.tmpRewardLane), safeSub(toBlockNumber, fromBlockNumber)); } function getParamsByBlockNumber(uint256 _blockNumber) internal view returns (uint256, uint256, uint256) { uint256 _rewardPerBlock; uint256 _decrement; uint256 i; uint256 tmpthisPoint; uint256 pointLength = registeredPoints.length; if( pointLength > 0 ) { for(i = 0; i < pointLength; i++) { RewardVelocityPoint memory point = registeredPoints[i]; if(_blockNumber >= point.blockNumber && 0 != point.blockNumber) { tmpthisPoint = i; _rewardPerBlock = point.rewardPerBlock; _decrement = point.decrementUnitPerBlock; } else if( 0 == point.blockNumber ) continue; else break; } } RewardVelocityPoint memory point = registeredPoints[tmpthisPoint]; _rewardPerBlock = point.rewardPerBlock; _decrement = point.decrementUnitPerBlock; if(_blockNumber > point.blockNumber) { _rewardPerBlock = safeSub(_rewardPerBlock, safeMul(_decrement, safeSub(_blockNumber, point.blockNumber) ) ); } return (i, _rewardPerBlock, _decrement); } function getUserPoolRate(address userAddr, uint256 fromBlockNumber, uint256 toBlockNumber) external view returns (uint256) { return getPoolRate(userAddr, fromBlockNumber, toBlockNumber); } function getModelPoolRate(uint256 fromBlockNumber, uint256 toBlockNumber) external view returns (uint256) { return getPoolRate(address(0), fromBlockNumber, toBlockNumber); } }
Set up memory variables used for calculation temporarily. Check whether this reward velocity point is valid and has//
function _updateRewardLaneView(uint256 fromBlockNumber) internal view returns (uint256) { UpdateRewardLaneModel memory vars; vars.len = registeredPoints.length; vars.memTotalDeposit = totalDeposited; if(fromBlockNumber == 0){ vars.tmpPassedPoint = vars.memPassedPoint = 0; vars.memThisBlockNum = block.number; vars.tmpLastBlockNum = vars.memLastBlockNum = 0; vars.tmpRewardLane = vars.memRewardLane = 0; vars.tmpRewardPerBlock = vars.memRewardPerBlock = 0; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock = 0; vars.tmpPassedPoint = vars.memPassedPoint = passedPoint; vars.memThisBlockNum = block.number; vars.tmpLastBlockNum = vars.memLastBlockNum = fromBlockNumber; vars.tmpRewardLane = vars.memRewardLane = rewardLane; vars.tmpRewardPerBlock = vars.memRewardPerBlock = rewardPerBlock; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock = decrementUnitPerBlock; } for(uint256 i=vars.memPassedPoint; i<vars.len; i++) { RewardVelocityPoint memory point = registeredPoints[i]; not applied yet. if(vars.tmpLastBlockNum < point.blockNumber && point.blockNumber <= vars.memThisBlockNum) { vars.tmpPassedPoint = i+1; vars.tmpBlockDelta = safeSub(point.blockNumber, vars.tmpLastBlockNum); (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); vars.tmpLastBlockNum = point.blockNumber; vars.tmpRewardPerBlock = point.rewardPerBlock; vars.tmpDecrementUnitPerBlock = point.decrementUnitPerBlock; reward velocity points) break; } if(vars.memThisBlockNum > vars.tmpLastBlockNum) { vars.tmpBlockDelta = safeSub(vars.memThisBlockNum, vars.tmpLastBlockNum); vars.tmpLastBlockNum = vars.memThisBlockNum; (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); } return vars.tmpRewardLane; }
2,543,083
./partial_match/5/0xA109b34B1974C1f6BA554607F46E202926728E14/sources/src/CDPVault.sol
Updates a position's collateral and normalized debt balances This is the only method which is allowed to modify a position's collateral and normalized debt balances update collateral and normalized debt amounts by the deltas position either has no debt or more debt than the debt floor store the position's balances
function _modifyPosition( address owner, Position memory position, PositionIRS memory positionIRS, int256 deltaCollateral, int256 deltaNormalDebt, uint256 totalNormalDebt_ ) internal returns (Position memory) { position.collateral = add(position.collateral, deltaCollateral); position.normalDebt = add(position.normalDebt, deltaNormalDebt); if (position.normalDebt != 0 && calculateDebt(position.normalDebt, positionIRS.snapshotRateAccumulator, positionIRS.accruedRebate) < uint256(vaultConfig.debtFloor) ) revert CDPVault__modifyPosition_debtFloor(); positions[owner] = position; emit ModifyPosition(owner, deltaCollateral, deltaNormalDebt, add(totalNormalDebt_, deltaNormalDebt)); return position; }
16,850,905
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ /** * @title CXIP ERC721 * @author CXIP-Labs * @notice A smart contract for minting and managing ERC721 NFTs. * @dev The entire logic and functionality of the smart contract is self-contained. */ contract CxipERC721 { /** * @dev Stores default collection data: name, symbol, and royalties. */ CollectionData private _collectionData; /** * @dev Internal last minted token id, to allow for auto-increment. */ uint256 private _currentTokenId; /** * @dev Array of all token ids in collection. */ uint256[] private _allTokens; /** * @dev Map of token id to array index of _ownedTokens. */ mapping(uint256 => uint256) private _ownedTokensIndex; /** * @dev Token id to wallet (owner) address map. */ mapping(uint256 => address) private _tokenOwner; /** * @dev 1-to-1 map of token id that was assigned an approved operator address. */ mapping(uint256 => address) private _tokenApprovals; /** * @dev Map of total tokens owner by a specific address. */ mapping(address => uint256) private _ownedTokensCount; /** * @dev Map of array of token ids owned by a specific address. */ mapping(address => uint256[]) private _ownedTokens; /** * @notice Map of full operator approval for a particular address. * @dev Usually utilised for supporting marketplace proxy wallets. */ mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Token data mapped by token id. */ mapping(uint256 => TokenData) private _tokenData; /** * @dev Address of admin user. Primarily used as an additional recover address. */ address private _admin; /** * @dev Address of contract owner. This address can run all onlyOwner functions. */ address private _owner; /** * @dev Simple tracker of all minted (not-burned) tokens. */ uint256 private _totalTokens; /** * @notice Event emitted when an token is minted, transfered, or burned. * @dev If from is empty, it's a mint. If to is empty, it's a burn. Otherwise, it's a transfer. * @param from Address from where token is being transfered. * @param to Address to where token is being transfered. * @param tokenId Token id that is being minted, Transfered, or burned. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @notice Event emitted when an address delegates power, for a token, to another address. * @dev Emits event that informs of address approving a third-party operator for a particular token. * @param wallet Address of the wallet configuring a token operator. * @param operator Address of the third-party operator approved for interaction. * @param tokenId A specific token id that is being authorised to operator. */ event Approval(address indexed wallet, address indexed operator, uint256 indexed tokenId); /** * @notice Event emitted when an address authorises an operator (third-party). * @dev Emits event that informs of address approving/denying a third-party operator. * @param wallet Address of the wallet configuring it's operator. * @param operator Address of the third-party operator that interacts on behalf of the wallet. * @param approved A boolean indicating whether approval was granted or revoked. */ event ApprovalForAll(address indexed wallet, address indexed operator, bool approved); /** * @notice Event emitted to signal to OpenSea that a permanent URI was created. * @dev Even though OpenSea advertises support for this, they do not listen to this event, and do not respond to it. * @param uri The permanent/static URL of the NFT. Cannot ever be changed again. * @param id Token id of the NFT. */ event PermanentURI(string uri, uint256 indexed id); /** * @notice Constructor is empty and not utilised. * @dev To make exact CREATE2 deployment possible, constructor is left empty. We utilize the "init" function instead. */ constructor() {} /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "CXIP: caller not an owner"); _; } /** * @notice Enables royaltiy functionality at the ERC721 level when ether is sent with no calldata. * @dev See implementation of _royaltiesFallback. */ receive() external payable { _royaltiesFallback(); } /** * @notice Enables royaltiy functionality at the ERC721 level no other function matches the call. * @dev See implementation of _royaltiesFallback. */ fallback() external { _royaltiesFallback(); } /** * @notice Gets the URI of the NFT on Arweave. * @dev Concatenates 2 sections of the arweave URI. * @param tokenId Id of the token. * @return string The URI. */ function arweaveURI(uint256 tokenId) external view returns (string memory) { return string(abi.encodePacked("https://arweave.net/", _tokenData[tokenId].arweave, _tokenData[tokenId].arweave2)); } /** * @notice Gets the URI of the NFT backup from CXIP. * @dev Concatenates to https://nft.cxip.io/. * @return string The URI. */ function contractURI() external view returns (string memory) { return string(abi.encodePacked("https://nft.cxip.io/", Strings.toHexString(address(this)), "/")); } /** * @notice Gets the creator's address. * @dev If the token Id doesn't exist it will return zero address. * @param tokenId Id of the token. * @return address Creator's address. */ function creator(uint256 tokenId) external view returns (address) { return _tokenData[tokenId].creator; } /** * @notice Gets the HTTP URI of the token. * @dev Concatenates to the baseURI. * @return string The URI. */ function httpURI(uint256 tokenId) external view returns (string memory) { return string(abi.encodePacked(baseURI(), "/", Strings.toHexString(tokenId))); } /** * @notice Gets the IPFS URI * @dev Concatenates to the IPFS domain. * @param tokenId Id of the token. * @return string The URI. */ function ipfsURI(uint256 tokenId) external view returns (string memory) { return string(abi.encodePacked("https://ipfs.io/ipfs/", _tokenData[tokenId].ipfs, _tokenData[tokenId].ipfs2)); } /** * @notice Gets the name of the collection. * @dev Uses two names to extend the max length of the collection name in bytes * @return string The collection name. */ function name() external view returns (string memory) { return string(abi.encodePacked(Bytes.trim(_collectionData.name), Bytes.trim(_collectionData.name2))); } /** * @notice Gets the hash of the NFT data used to create it. * @dev Payload is used for verification. * @param tokenId The Id of the token. * @return bytes32 The hash. */ function payloadHash(uint256 tokenId) external view returns (bytes32) { return _tokenData[tokenId].payloadHash; } /** * @notice Gets the signature of the signed NFT data used to create it. * @dev Used for signature verification. * @param tokenId The Id of the token. * @return Verification a struct containing v, r, s values of the signature. */ function payloadSignature(uint256 tokenId) external view returns (Verification memory) { return _tokenData[tokenId].payloadSignature; } /** * @notice Gets the address of the creator. * @dev The creator signs a payload while creating the NFT. * @param tokenId The Id of the token. * @return address The creator. */ function payloadSigner(uint256 tokenId) external view returns (address) { return _tokenData[tokenId].creator; } /** * @notice Shows the interfaces the contracts support * @dev Must add new 4 byte interface Ids here to acknowledge support * @param interfaceId ERC165 style 4 byte interfaceId. * @return bool True if supported. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { if ( interfaceId == 0x01ffc9a7 || // ERC165 interfaceId == 0x80ac58cd || // ERC721 // || interfaceId == 0x780e9d63 // ERC721Enumerable interfaceId == 0x5b5e139f || // ERC721Metadata interfaceId == 0x150b7a02 || // ERC721TokenReceiver interfaceId == 0xe8a3d485 || // contractURI() IPA1D(getRegistry().getPA1D()).supportsInterface(interfaceId) ) { return true; } else { return false; } } /** * @notice Gets the collection's symbol. * @dev Trims the symbol. * @return string The symbol. */ function symbol() external view returns (string memory) { return string(Bytes.trim(_collectionData.symbol)); } /** * @notice Get's the URI of the token. * @dev Defaults the the Arweave URI * @param tokenId The Id of the token. * @return string The URI. */ function tokenURI(uint256 tokenId) external view returns (string memory) { return string(abi.encodePacked("https://arweave.net/", _tokenData[tokenId].arweave, _tokenData[tokenId].arweave2)); } /** Disabled due to tokenEnumeration not enabled. * @notice Get list of tokens owned by wallet. * @param wallet The wallet address to get tokens for. * @return uint256[] Returns an array of token ids owned by wallet. function tokensOfOwner(address wallet) external view returns (uint256[] memory) { return _ownedTokens[wallet]; } */ /** * @notice Checks if a given hash matches a payload hash. * @dev Uses sha256 instead of keccak. * @param hash The hash to check. * @param payload The payload prehashed. * @return bool True if the hashes match. */ function verifySHA256(bytes32 hash, bytes calldata payload) external pure returns (bool) { bytes32 thePayloadHash = sha256(payload); return hash == thePayloadHash; } /** * @notice Adds a new address to the token's approval list. * @dev Requires the sender to be in the approved addresses. * @param to The address to approve. * @param tokenId The affected token. */ function approve(address to, uint256 tokenId) public { address tokenOwner = _tokenOwner[tokenId]; if (to != tokenOwner && _isApproved(msg.sender, tokenId)) { _tokenApprovals[tokenId] = to; emit Approval(tokenOwner, to, tokenId); } } /** * @notice Burns the token. * @dev The sender must be the owner or approved. * @param tokenId The token to burn. */ function burn(uint256 tokenId) public { if (_isApproved(msg.sender, tokenId)) { address wallet = _tokenOwner[tokenId]; require(!Address.isZero(wallet)); _clearApproval(tokenId); _tokenOwner[tokenId] = address(0); emit Transfer(wallet, address(0), tokenId); // _removeTokenFromOwnerEnumeration(wallet, tokenId); // uint256 index = _allTokens.length; // index--; // if (index == 0) { // delete _allTokens; // } else { // delete _allTokens[index]; // } _totalTokens -= 1; delete _tokenData[tokenId]; } } /** * @notice Initializes the collection. * @dev Special function to allow a one time initialisation on deployment. Also configures and deploys royalties. * @param newOwner The owner of the collection. * @param collectionData The collection data. */ function init(address newOwner, CollectionData calldata collectionData) public { require(Address.isZero(_admin), "CXIP: already initialized"); _admin = msg.sender; // temporary set to self, to pass rarible royalties logic trap _owner = address(this); _collectionData = collectionData; IPA1D(address(this)).init (0, payable(collectionData.royalties), collectionData.bps); // set to actual owner _owner = newOwner; } /** Disabled since this flow has not been agreed on. * @notice Transfer received NFTs to contract owner. * @dev Automatically transfer NFTs out of this smart contract to contract owner. This uses gas from sender. * @param _operator The smart contract where NFT is minted/operated. * @param _from The address from where NFT is being transfered from. * @param _tokenId NFT token id. * @param _data Arbitrary data that could be used for special function calls. * @return bytes4 Returns the onERC721Received interfaceId, to confirm successful receipt of NFT transfer. * function onERC721Received( address _operator, address /*_from*\/, uint256 _tokenId, bytes calldata _data ) public returns (bytes4) { ICxipERC721(_operator).safeTransferFrom( payable(address(this)), _owner, _tokenId, _data ); return 0x150b7a02; } */ /** * @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. * @param from cannot be the zero address. * @param to cannot be the zero address. * @param tokenId token must exist and be owned by `from`. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public payable { safeTransferFrom(from, to, tokenId, ""); } /** * @notice Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings. * are aware of the ERC721 protocol to prevent tokens from being forever locked. * @param from cannot be the zero address. * @param to cannot be the zero address. * @param tokenId token must exist and be owned by `from`. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory /*_data*/ ) public payable { if (_isApproved(msg.sender, tokenId)) { _transferFrom(from, to, tokenId); } } /** * @notice Adds a new approved operator. * @dev Allows platforms to sell/transfer all your NFTs. Used with proxy contracts like OpenSea/Rarible. * @param to The address to approve. * @param approved Turn on or off approval status. */ function setApprovalForAll(address to, bool approved) public { if (to != msg.sender) { _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } else { assert(false); } } /** * @notice Transfers `tokenId` token from `from` to `to`. * @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * @param from cannot be the zero address. * @param to cannot be the zero address. * @param tokenId token must be owned by `from`. */ function transferFrom( address from, address to, uint256 tokenId ) public payable { transferFrom(from, to, tokenId, ""); } /** * @notice Transfers `tokenId` token from `from` to `to`. * @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings. * @param from cannot be the zero address. * @param to cannot be the zero address. * @param tokenId token must be owned by `from`. */ function transferFrom( address from, address to, uint256 tokenId, bytes memory /*_data*/ ) public payable { if (_isApproved(msg.sender, tokenId)) { _transferFrom(from, to, tokenId); } } /** * @notice Mints and NFT. * @dev Includes event with the Arwave token URI. * @param id The new tokenId. * @param tokenData The token data for the NFT. * @return uint256 The new tokenId. */ function cxipMint(uint256 id, TokenData calldata tokenData) public onlyOwner returns (uint256) { if (id == 0) { _currentTokenId += 1; id = _currentTokenId; } _mint(tokenData.creator, id); _tokenData[id] = tokenData; emit PermanentURI(string(abi.encodePacked("https://arweave.net/", tokenData.arweave, tokenData.arweave2)), id); return id; } /** * @notice Sets a name for the collection. * @dev The name is split in two for gas optimization. * @param newName First part of name. * @param newName2 Second part of name. */ function setName(bytes32 newName, bytes32 newName2) public onlyOwner { _collectionData.name = newName; _collectionData.name2 = newName2; } /** * @notice Set a symbol for the collection. * @dev This is the ticker symbol for smart contract that shows up on EtherScan. * @param newSymbol The ticker symbol to set for smart contract. */ function setSymbol(bytes32 newSymbol) public onlyOwner { _collectionData.symbol = newSymbol; } /** * @notice Transfers ownership of the collection. * @dev Can't be the zero address. * @param newOwner Address of new owner. */ function transferOwnership(address newOwner) public onlyOwner { if (!Address.isZero(newOwner)) { _owner = newOwner; } } /** Disabled due to tokenEnumeration not enabled. * @notice Get total number of tokens owned by wallet. * @dev Used to see total amount of tokens owned by a specific wallet. * @param wallet Address for which to get token balance. * @return uint256 Returns an integer, representing total amount of tokens held by address. * function balanceOf(address wallet) public view returns (uint256) { return _ownedTokensCount[wallet]; } */ /** * @notice Get a base URI for the token. * @dev Concatenates with the CXIP domain name. * @return string the token URI. */ function baseURI() public view returns (string memory) { return string(abi.encodePacked("https://cxip.io/nft/", Strings.toHexString(address(this)))); } /** * @notice Gets the approved address for the token. * @dev Single operator set for a specific token. Usually used for one-time very specific authorisations. * @param tokenId Token id to get approved operator for. * @return address Approved address for token. */ function getApproved(uint256 tokenId) public view returns (address) { return _tokenApprovals[tokenId]; } /** * @notice Get the associated identity for the collection. * @dev Goes up the chain to read from the registry. * @return address Identity contract address. */ function getIdentity() public view returns (address) { return ICxipProvenance(getRegistry().getProvenance()).getWalletIdentity(_owner); } /** * @notice Checks if the address is approved. * @dev Includes references to OpenSea and Rarible marketplace proxies. * @param wallet Address of the wallet. * @param operator Address of the marketplace operator. * @return bool True if approved. */ function isApprovedForAll(address wallet, address operator) public view returns (bool) { return (_operatorApprovals[wallet][operator] || // Rarible Transfer Proxy 0x4feE7B061C97C9c496b01DbcE9CDb10c02f0a0Be == operator || // OpenSea Transfer Proxy address(OpenSeaProxyRegistry(0xa5409ec958C83C3f309868babACA7c86DCB077c1).proxies(wallet)) == operator); } /** * @notice Check if the sender is the owner. * @dev The owner could also be the admin or identity contract of the owner. * @return bool True if owner. */ function isOwner() public view returns (bool) { return (msg.sender == _owner || msg.sender == _admin || isIdentityWallet(msg.sender)); } /** * @notice Gets the owner's address. * @dev _owner is first set in init. * @return address Of ower. */ function owner() public view returns (address) { return _owner; } /** * @notice Checks who the owner of a token is. * @dev The token must exist. * @param tokenId The token to look up. * @return address Owner of the token. */ function ownerOf(uint256 tokenId) public view returns (address) { address tokenOwner = _tokenOwner[tokenId]; require(!Address.isZero(tokenOwner), "ERC721: token does not exist"); return tokenOwner; } /** Disabled due to tokenEnumeration not enabled. * @notice Get token by index instead of token id. * @dev Helpful for token enumeration where token id info is not yet available. * @param index Index of token in array. * @return uint256 Returns the token id of token located at that index. function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } */ /** Disabled due to tokenEnumeration not enabled. * @notice Get token from wallet by index instead of token id. * @dev Helpful for wallet token enumeration where token id info is not yet available. Use in conjunction with balanceOf function. * @param wallet Specific address for which to get token for. * @param index Index of token in array. * @return uint256 Returns the token id of token located at that index in specified wallet. * function tokenOfOwnerByIndex( address wallet, uint256 index ) public view returns (uint256) { require(index < balanceOf(wallet)); return _ownedTokens[wallet][index]; } */ /** Disabled due to tokenEnumeration not enabled. * @notice Total amount of tokens in the collection. * @dev Ignores burned tokens. * @return uint256 Returns the total number of active (not burned) tokens. * function totalSupply() public view returns (uint256) { return _allTokens.length; } */ /** * @notice Total amount of tokens in the collection. * @dev Ignores burned tokens. * @return uint256 Returns the total number of active (not burned) tokens. */ function totalSupply() public view returns (uint256) { return _totalTokens; } /** * @notice Empty function that is triggered by external contract on NFT transfer. * @dev We have this blank function in place to make sure that external contract sending in NFTs don't error out. * @dev Since it's not being used, the _operator variable is commented out to avoid compiler warnings. * @dev Since it's not being used, the _from variable is commented out to avoid compiler warnings. * @dev Since it's not being used, the _tokenId variable is commented out to avoid compiler warnings. * @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings. * @return bytes4 Returns the interfaceId of onERC721Received. */ function onERC721Received( address, /*_operator*/ address, /*_from*/ uint256, /*_tokenId*/ bytes calldata /*_data*/ ) public pure returns (bytes4) { return 0x150b7a02; } /** * @notice Allows retrieval of royalties from the contract. * @dev This is a default fallback to ensure the royalties are available. */ function _royaltiesFallback() internal { address _target = getRegistry().getPA1D(); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), _target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Checks if an address is an identity contract. * @dev It must also be registred. * @param sender Address to check if registered to identity. * @return bool True if registred identity. */ function isIdentityWallet(address sender) internal view returns (bool) { address identity = getIdentity(); if (Address.isZero(identity)) { return false; } return ICxipIdentity(identity).isWalletRegistered(sender); } /** * @dev Get the top-level CXIP Registry smart contract. Function must always be internal to prevent miss-use/abuse through bad programming practices. * @return ICxipRegistry The address of the top-level CXIP Registry smart contract. */ function getRegistry() internal pure returns (ICxipRegistry) { return ICxipRegistry(0xC267d41f81308D7773ecB3BDd863a902ACC01Ade); } /** Disabled due to tokenEnumeration not enabled. * @dev Add a newly minted token into managed list of tokens. * @param to Address of token owner for which to add the token. * @param tokenId Id of token to add. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokensCount[to]; _ownedTokensCount[to]++; _ownedTokens[to].push(tokenId); } */ /** * @notice Deletes a token from the approval list. * @dev Removes from count. * @param tokenId T. */ function _clearApproval(uint256 tokenId) private { delete _tokenApprovals[tokenId]; } /** * @notice Mints an NFT. * @dev Can to mint the token to the zero address and the token cannot already exist. * @param to Address to mint to. * @param tokenId The new token. */ function _mint(address to, uint256 tokenId) private { if (Address.isZero(to) || _exists(tokenId)) { assert(false); } _tokenOwner[tokenId] = to; emit Transfer(address(0), to, tokenId); // _addTokenToOwnerEnumeration(to, tokenId); _totalTokens += 1; // _allTokens.push(tokenId); } /** Disabled due to tokenEnumeration not enabled. * @dev Remove a token from managed list of tokens. * @param from Address of token owner for which to remove the token. * @param tokenId Id of token to remove. function _removeTokenFromOwnerEnumeration( address from, uint256 tokenId ) private { _ownedTokensCount[from]--; uint256 lastTokenIndex = _ownedTokensCount[from]; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if(tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; _ownedTokensIndex[lastTokenId] = tokenIndex; } if(lastTokenIndex == 0) { delete _ownedTokens[from]; } else { delete _ownedTokens[from][lastTokenIndex]; } } */ /** * @dev Primary internal function that handles the transfer/mint/burn functionality. * @param from Address from where token is being transferred. Zero address means it is being minted. * @param to Address to whom the token is being transferred. Zero address means it is being burned. * @param tokenId Id of token that is being transferred/minted/burned. */ function _transferFrom( address from, address to, uint256 tokenId ) private { if (_tokenOwner[tokenId] == from && !Address.isZero(to)) { _clearApproval(tokenId); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); // _removeTokenFromOwnerEnumeration(from, tokenId); // _addTokenToOwnerEnumeration(to, tokenId); } else { assert(false); } } /** * @notice Checks if the token owner exists. * @dev If the address is the zero address no owner exists. * @param tokenId The affected token. * @return bool True if it exists. */ function _exists(uint256 tokenId) private view returns (bool) { address tokenOwner = _tokenOwner[tokenId]; return !Address.isZero(tokenOwner); } /** * @notice Checks if the address is an approved one. * @dev Uses inlined checks for different usecases of approval. * @param spender Address of the spender. * @param tokenId The affected token. * @return bool True if approved. */ function _isApproved(address spender, uint256 tokenId) private view returns (bool) { require(_exists(tokenId)); address tokenOwner = _tokenOwner[tokenId]; return ( spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, spender) ); } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function isZero(address account) internal pure returns (bool) { return (account == address(0)); } } library Bytes { function getBoolean(uint192 _packedBools, uint192 _boolNumber) internal pure returns (bool) { uint192 flag = (_packedBools >> _boolNumber) & uint192(1); return (flag == 1 ? true : false); } function setBoolean( uint192 _packedBools, uint192 _boolNumber, bool _value ) internal pure returns (uint192) { if (_value) { return _packedBools | (uint192(1) << _boolNumber); } else { return _packedBools & ~(uint192(1) << _boolNumber); } } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { 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) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function trim(bytes32 source) internal pure returns (bytes memory) { uint256 temp = uint256(source); uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return slice(abi.encodePacked(source), 32 - length, length); } } struct CollectionData { bytes32 name; bytes32 name2; bytes32 symbol; address royalties; uint96 bps; } interface ICxipERC721 { function arweaveURI(uint256 tokenId) external view returns (string memory); function contractURI() external view returns (string memory); function creator(uint256 tokenId) external view returns (address); function httpURI(uint256 tokenId) external view returns (string memory); function ipfsURI(uint256 tokenId) external view returns (string memory); function name() external view returns (string memory); function payloadHash(uint256 tokenId) external view returns (bytes32); function payloadSignature(uint256 tokenId) external view returns (Verification memory); function payloadSigner(uint256 tokenId) external view returns (address); function supportsInterface(bytes4 interfaceId) external view returns (bool); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); /* Disabled due to tokenEnumeration not enabled. function tokensOfOwner( address wallet ) external view returns (uint256[] memory); */ function verifySHA256(bytes32 hash, bytes calldata payload) external pure returns (bool); function approve(address to, uint256 tokenId) external; function burn(uint256 tokenId) external; function init(address newOwner, CollectionData calldata collectionData) external; /* Disabled since this flow has not been agreed on. function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); */ function safeTransferFrom( address from, address to, uint256 tokenId ) external payable; function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) external payable; function setApprovalForAll(address to, bool approved) external; function transferFrom( address from, address to, uint256 tokenId ) external payable; function transferFrom( address from, address to, uint256 tokenId, bytes memory data ) external payable; function cxipMint(uint256 id, TokenData calldata tokenData) external returns (uint256); function setApprovalForAll( address from, address to, bool approved ) external; function setName(bytes32 newName, bytes32 newName2) external; function setSymbol(bytes32 newSymbol) external; function transferOwnership(address newOwner) external; /* // Disabled due to tokenEnumeration not enabled. function balanceOf(address wallet) external view returns (uint256); */ function baseURI() external view returns (string memory); function getApproved(uint256 tokenId) external view returns (address); function getIdentity() external view returns (address); function isApprovedForAll(address wallet, address operator) external view returns (bool); function isOwner() external view returns (bool); function owner() external view returns (address); function ownerOf(uint256 tokenId) external view returns (address); /* Disabled due to tokenEnumeration not enabled. function tokenByIndex(uint256 index) external view returns (uint256); */ /* Disabled due to tokenEnumeration not enabled. function tokenOfOwnerByIndex( address wallet, uint256 index ) external view returns (uint256); */ /* Disabled due to tokenEnumeration not enabled. function totalSupply() external view returns (uint256); */ function totalSupply() external view returns (uint256); function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure returns (bytes4); } interface ICxipIdentity { function addSignedWallet( address newWallet, uint8 v, bytes32 r, bytes32 s ) external; function addWallet(address newWallet) external; function connectWallet() external; function createERC721Token( address collection, uint256 id, TokenData calldata tokenData, Verification calldata verification ) external returns (uint256); function createERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData ) external returns (address); function createCustomERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData, bytes32 slot, bytes memory bytecode ) external returns (address); function init(address wallet, address secondaryWallet) external; function getAuthorizer(address wallet) external view returns (address); function getCollectionById(uint256 index) external view returns (address); function getCollectionType(address collection) external view returns (InterfaceType); function getWallets() external view returns (address[] memory); function isCollectionCertified(address collection) external view returns (bool); function isCollectionRegistered(address collection) external view returns (bool); function isNew() external view returns (bool); function isOwner() external view returns (bool); function isTokenCertified(address collection, uint256 tokenId) external view returns (bool); function isTokenRegistered(address collection, uint256 tokenId) external view returns (bool); function isWalletRegistered(address wallet) external view returns (bool); function listCollections(uint256 offset, uint256 length) external view returns (address[] memory); function nextNonce(address wallet) external view returns (uint256); function totalCollections() external view returns (uint256); function isCollectionOpen(address collection) external pure returns (bool); } interface ICxipProvenance { function createIdentity( bytes32 saltHash, address wallet, uint8 v, bytes32 r, bytes32 s ) external returns (uint256, address); function createIdentityBatch( bytes32 saltHash, address[] memory wallets, uint8[] memory V, bytes32[] memory RS ) external returns (uint256, address); function getIdentity() external view returns (address); function getWalletIdentity(address wallet) external view returns (address); function informAboutNewWallet(address newWallet) external; function isIdentityValid(address identity) external view returns (bool); function nextNonce(address wallet) external view returns (uint256); } interface ICxipRegistry { function getAsset() external view returns (address); function getAssetSigner() external view returns (address); function getAssetSource() external view returns (address); function getCopyright() external view returns (address); function getCopyrightSource() external view returns (address); function getCustomSource(bytes32 name) external view returns (address); function getCustomSourceFromString(string memory name) external view returns (address); function getERC1155CollectionSource() external view returns (address); function getERC721CollectionSource() external view returns (address); function getIdentitySource() external view returns (address); function getPA1D() external view returns (address); function getPA1DSource() external view returns (address); function getProvenance() external view returns (address); function getProvenanceSource() external view returns (address); function owner() external view returns (address); function setAsset(address proxy) external; function setAssetSigner(address source) external; function setAssetSource(address source) external; function setCopyright(address proxy) external; function setCopyrightSource(address source) external; function setCustomSource(string memory name, address source) external; function setERC1155CollectionSource(address source) external; function setERC721CollectionSource(address source) external; function setIdentitySource(address source) external; function setPA1D(address proxy) external; function setPA1DSource(address source) external; function setProvenance(address proxy) external; function setProvenanceSource(address source) external; } // This is a 256 value limit (uint8) enum InterfaceType { NULL, // 0 ERC20, // 1 ERC721, // 2 ERC1155 // 3 } interface IPA1D { function init( uint256 tokenId, address payable receiver, uint256 bp ) external; function configurePayouts(address payable[] memory addresses, uint256[] memory bps) external; function getPayoutInfo() external view returns (address payable[] memory addresses, uint256[] memory bps); function getEthPayout() external; function getTokenPayout(address tokenAddress) external; function getTokenPayoutByName(string memory tokenName) external; function getTokensPayout(address[] memory tokenAddresses) external; function getTokensPayoutByName(string[] memory tokenNames) external; function supportsInterface(bytes4 interfaceId) external pure returns (bool); function setRoyalties( uint256 tokenId, address payable receiver, uint256 bp ) external; function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256); function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function tokenCreator(address contractAddress, uint256 tokenId) external view returns (address); function calculateRoyaltyFee( address contractAddress, uint256 tokenId, uint256 amount ) external view returns (uint256); function marketContract() external view returns (address); function tokenCreators(uint256 tokenId) external view returns (address); function bidSharesForToken(uint256 tokenId) external view returns (Zora.BidShares memory bidShares); function getStorageSlot(string calldata slot) external pure returns (bytes32); function getTokenAddress(string memory tokenName) external view returns (address); } contract OpenSeaOwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OpenSeaOwnableDelegateProxy) public proxies; } library Strings { function toHexString(address account) internal pure returns (string memory) { return toHexString(uint256(uint160(account))); } 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] = bytes16("0123456789abcdef")[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } struct Token { address collection; uint256 tokenId; InterfaceType tokenType; address creator; } struct TokenData { bytes32 payloadHash; Verification payloadSignature; address creator; bytes32 arweave; bytes11 arweave2; bytes32 ipfs; bytes14 ipfs2; } // This is a 256 value limit (uint8) enum UriType { ARWEAVE, // 0 IPFS, // 1 HTTP // 2 } struct Verification { bytes32 r; bytes32 s; uint8 v; } library Zora { struct Decimal { uint256 value; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft Decimal prevOwner; // % of sale value that goes to the original creator of the nft Decimal creator; // % of sale value that goes to the seller (current owner) of the nft Decimal owner; } }
Mints an NFT. Can to mint the token to the zero address and the token cannot already exist. to Address to mint to. tokenId The new token./
function _mint(address to, uint256 tokenId) private { if (Address.isZero(to) || _exists(tokenId)) { assert(false); } _tokenOwner[tokenId] = to; emit Transfer(address(0), to, tokenId);
411,456
./full_match/1/0x1a50DC5d7F23D5aF1358AF432879976d612334de/sources/contracts/FarmingRewards.sol
Get addresses who exist in farming rewards return Balance of how many currently staked LP tokens specific account/
function getActiveAccountCount() external view returns (uint256) { uint256 count; for(uint256 i = 1; i <= currentCountAccounts; i++) { if (accountAddressById[i] != address(0)) { count = count + 1; } } return count; }
2,969,590
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title iOVM_CrossDomainMessenger */ interface iOVM_CrossDomainMessenger { /********** * Events * **********/ event SentMessage(bytes message); event RelayedMessage(bytes32 msgHash); event FailedRelayedMessage(bytes32 msgHash); /************* * Variables * *************/ function xDomainMessageSender() external view returns (address); /******************** * Public Functions * ********************/ /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "../../iOVM/bridge/messaging/iOVM_CrossDomainMessenger.sol"; /** * @title OVM_CrossDomainEnabled * @dev Helper contract for contracts performing cross-domain communications * * Compiler used: defined by inheriting contract * Runtime target: defined by inheriting contract */ contract OVM_CrossDomainEnabled { /************* * Variables * *************/ // Messenger contract used to send and recieve messages from the other domain. address public messenger; /*************** * Constructor * ***************/ /** * @param _messenger Address of the CrossDomainMessenger on the current layer. */ constructor( address _messenger ) { messenger = _messenger; } /********************** * Function Modifiers * **********************/ /** * Enforces that the modified function is only callable by a specific cross-domain account. * @param _sourceDomainAccount The only account on the originating domain which is * authenticated to call this function. */ modifier onlyFromCrossDomainAccount( address _sourceDomainAccount ) { require( msg.sender == address(getCrossDomainMessenger()), "OVM_XCHAIN: messenger contract unauthenticated" ); require( getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount, "OVM_XCHAIN: wrong sender of cross-domain message" ); _; } /********************** * Internal Functions * **********************/ /** * Gets the messenger, usually from storage. This function is exposed in case a child contract * needs to override. * @return The address of the cross-domain messenger contract which should be used. */ function getCrossDomainMessenger() internal virtual returns ( iOVM_CrossDomainMessenger ) { return iOVM_CrossDomainMessenger(messenger); } /** * Sends a message to an account on another domain * @param _crossDomainTarget The intended recipient on the destination domain * @param _message The data to send to the target (usually calldata to a function with * `onlyFromCrossDomainAccount()`) * @param _gasLimit The gasLimit for the receipt of the message on the target domain. */ function sendCrossDomainMessage( address _crossDomainTarget, uint32 _gasLimit, bytes memory _message ) internal { getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol"; import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol"; import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol"; /* Library Imports */ import { ERC165Checker } from "@openzeppelin/contracts/introspection/ERC165Checker.sol"; import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { IL2StandardERC20 } from "../../../libraries/standards/IL2StandardERC20.sol"; /** * @title OVM_L2StandardBridge * @dev The L2 Standard bridge is a contract which works together with the L1 Standard bridge to * enable ETH and ERC20 transitions between L1 and L2. * This contract acts as a minter for new tokens when it hears about deposits into the L1 Standard * bridge. * This contract also acts as a burner of the tokens intended for withdrawal, informing the L1 * bridge to release L1 funds. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2StandardBridge is iOVM_L2ERC20Bridge, OVM_CrossDomainEnabled { /******************************** * External Contract References * ********************************/ address public l1TokenBridge; /*************** * Constructor * ***************/ /** * @param _l2CrossDomainMessenger Cross-domain messenger used by this contract. * @param _l1TokenBridge Address of the L1 bridge deployed to the main chain. */ constructor( address _l2CrossDomainMessenger, address _l1TokenBridge ) OVM_CrossDomainEnabled(_l2CrossDomainMessenger) { l1TokenBridge = _l1TokenBridge; } /*************** * Withdrawing * ***************/ /** * @inheritdoc iOVM_L2ERC20Bridge */ function withdraw( address _l2Token, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) external override virtual { _initiateWithdrawal( _l2Token, msg.sender, msg.sender, _amount, _l1Gas, _data ); } /** * @inheritdoc iOVM_L2ERC20Bridge */ function withdrawTo( address _l2Token, address _to, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) external override virtual { _initiateWithdrawal( _l2Token, msg.sender, _to, _amount, _l1Gas, _data ); } /** * @dev Performs the logic for deposits by storing the token and informing the L2 token Gateway * of the deposit. * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _from Account to pull the deposit from on L2. * @param _to Account to give the withdrawal to on L1. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateWithdrawal( address _l2Token, address _from, address _to, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) internal { // When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2 // usage IL2StandardERC20(_l2Token).burn(msg.sender, _amount); // Construct calldata for l1TokenBridge.finalizeERC20Withdrawal(_to, _amount) address l1Token = IL2StandardERC20(_l2Token).l1Token(); bytes memory message; if (_l2Token == Lib_PredeployAddresses.OVM_ETH) { message = abi.encodeWithSelector( iOVM_L1StandardBridge.finalizeETHWithdrawal.selector, _from, _to, _amount, _data ); } else { message = abi.encodeWithSelector( iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector, l1Token, _l2Token, _from, _to, _amount, _data ); } // Send message up to L1 bridge sendCrossDomainMessage( l1TokenBridge, _l1Gas, message ); emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data); } /************************************ * Cross-chain Function: Depositing * ************************************/ /** * @inheritdoc iOVM_L2ERC20Bridge */ function finalizeDeposit( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, bytes calldata _data ) external override virtual onlyFromCrossDomainAccount(l1TokenBridge) { // Check the target token is compliant and // verify the deposited token on L1 matches the L2 deposited token representation here if ( ERC165Checker.supportsInterface(_l2Token, 0x1d1d8b63) && _l1Token == IL2StandardERC20(_l2Token).l1Token() ) { // When a deposit is finalized, we credit the account on L2 with the same amount of // tokens. IL2StandardERC20(_l2Token).mint(_to, _amount); emit DepositFinalized(_l1Token, _l2Token, _from, _to, _amount, _data); } else { // Either the L2 token which is being deposited-into disagrees about the correct address // of its L1 token, or does not support the correct interface. // This should only happen if there is a malicious L2 token, or if a user somehow // specified the wrong L2 token address to deposit into. // In either case, we stop the process here and construct a withdrawal // message so that users can get their funds out in some cases. // There is no way to prevent malicious token contracts altogether, but this does limit // user error and mitigate some forms of malicious contract behavior. bytes memory message = abi.encodeWithSelector( iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector, _l1Token, _l2Token, _to, // switched the _to and _from here to bounce back the deposit to the sender _from, _amount, _data ); // Send message up to L1 bridge sendCrossDomainMessage( l1TokenBridge, 0, message ); emit DepositFailed(_l1Token, _l2Token, _from, _to, _amount, _data); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; import "./iOVM_L1ERC20Bridge.sol"; /** * @title iOVM_L1StandardBridge */ interface iOVM_L1StandardBridge is iOVM_L1ERC20Bridge { /********** * Events * **********/ event ETHDepositInitiated ( address indexed _from, address indexed _to, uint256 _amount, bytes _data ); event ETHWithdrawalFinalized ( address indexed _from, address indexed _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev Deposit an amount of the ETH to the caller's balance on L2. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositETH ( uint32 _l2Gas, bytes calldata _data ) external payable; /** * @dev Deposit an amount of ETH to a recipient's balance on L2. * @param _to L2 address to credit the withdrawal to. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositETHTo ( address _to, uint32 _l2Gas, bytes calldata _data ) external payable; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. Since only the xDomainMessenger can call this function, it will never be called * before the withdrawal is finalized. * @param _from L2 address initiating the transfer. * @param _to L1 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeETHWithdrawal ( address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; /** * @title iOVM_L1ERC20Bridge */ interface iOVM_L1ERC20Bridge { /********** * Events * **********/ event ERC20DepositInitiated ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event ERC20WithdrawalFinalized ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev deposit an amount of the ERC20 to the caller's balance on L2. * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _amount Amount of the ERC20 to deposit * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositERC20 ( address _l1Token, address _l2Token, uint _amount, uint32 _l2Gas, bytes calldata _data ) external; /** * @dev deposit an amount of ERC20 to a recipient's balance on L2. * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _to L2 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositERC20To ( address _l1Token, address _l2Token, address _to, uint _amount, uint32 _l2Gas, bytes calldata _data ) external; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ERC20 token. * This call will fail if the initialized withdrawal from L2 has not been finalized. * * @param _l1Token Address of L1 token to finalizeWithdrawal for. * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _from L2 address initiating the transfer. * @param _to L1 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _data Data provided by the sender on L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeERC20Withdrawal ( address _l1Token, address _l2Token, address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; /** * @title iOVM_L2ERC20Bridge */ interface iOVM_L2ERC20Bridge { /********** * Events * **********/ event WithdrawalInitiated ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event DepositFinalized ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event DepositFailed ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev initiate a withdraw of some tokens to the caller's account on L1 * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function withdraw ( address _l2Token, uint _amount, uint32 _l1Gas, bytes calldata _data ) external; /** * @dev initiate a withdraw of some token to a recipient's account on L1. * @param _l2Token Address of L2 token where withdrawal is initiated. * @param _to L1 adress to credit the withdrawal to. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function withdrawTo ( address _l2Token, address _to, uint _amount, uint32 _l1Gas, bytes calldata _data ) external; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a deposit from L1 to L2, and credits funds to the recipient's balance of this * L2 token. This call will fail if it did not originate from a corresponding deposit in * OVM_l1TokenGateway. * @param _l1Token Address for the l1 token this is called with * @param _l2Token Address for the l2 token this is called with * @param _from Account to pull the deposit from on L2. * @param _to Address to receive the withdrawal at * @param _amount Amount of the token to withdraw * @param _data Data provider by the sender on L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeDeposit ( address _l1Token, address _l2Token, address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_PredeployAddresses */ library Lib_PredeployAddresses { address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000; address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address internal constant ECDSA_CONTRACT_ACCOUNT = 0x4200000000000000000000000000000000000003; address internal constant SEQUENCER_ENTRYPOINT = 0x4200000000000000000000000000000000000005; address payable internal constant OVM_ETH = 0x4200000000000000000000000000000000000006; // solhint-disable-next-line max-line-length address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; // solhint-disable-next-line max-line-length address internal constant EXECUTION_MANAGER_WRAPPER = 0x420000000000000000000000000000000000000B; address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011; address internal constant ERC1820_REGISTRY = 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.8.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol"; interface IL2StandardERC20 is IERC20, IERC165 { function l1Token() external returns (address); function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; event Mint(address indexed _account, uint256 _amount); event Burn(address indexed _account, uint256 _amount); } // 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 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.5.0 <0.8.0; /* Library Imports */ import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { OVM_ETH } from "../predeploys/OVM_ETH.sol"; import { OVM_L2StandardBridge } from "../bridge/tokens/OVM_L2StandardBridge.sol"; /** * @title OVM_SequencerFeeVault * @dev Simple holding contract for fees paid to the Sequencer. Likely to be replaced in the future * but "good enough for now". * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_SequencerFeeVault { /************* * Constants * *************/ // Minimum ETH balance that can be withdrawn in a single withdrawal. uint256 public constant MIN_WITHDRAWAL_AMOUNT = 15 ether; /************* * Variables * *************/ // Address on L1 that will hold the fees once withdrawn. Dynamically initialized within l2geth. address public l1FeeWallet; /*************** * Constructor * ***************/ /** * @param _l1FeeWallet Initial address for the L1 wallet that will hold fees once withdrawn. * Currently HAS NO EFFECT in production because l2geth will mutate this storage slot during * the genesis block. This is ONLY for testing purposes. */ constructor( address _l1FeeWallet ) { l1FeeWallet = _l1FeeWallet; } /******************** * Public Functions * ********************/ function withdraw() public { uint256 balance = OVM_ETH(Lib_PredeployAddresses.OVM_ETH).balanceOf(address(this)); require( balance >= MIN_WITHDRAWAL_AMOUNT, // solhint-disable-next-line max-line-length "OVM_SequencerFeeVault: withdrawal amount must be greater than minimum withdrawal amount" ); OVM_L2StandardBridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo( Lib_PredeployAddresses.OVM_ETH, l1FeeWallet, balance, 0, bytes("") ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { L2StandardERC20 } from "../../libraries/standards/L2StandardERC20.sol"; import { IWETH9 } from "../../libraries/standards/IWETH9.sol"; /** * @title OVM_ETH * @dev The ETH predeploy provides an ERC20 interface for ETH deposited to Layer 2. Note that * unlike on Layer 1, Layer 2 accounts do not have a balance field. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ETH is L2StandardERC20, IWETH9 { /*************** * Constructor * ***************/ constructor() L2StandardERC20( Lib_PredeployAddresses.L2_STANDARD_BRIDGE, address(0), "Ether", "ETH" ) {} /****************************** * Custom WETH9 Functionality * ******************************/ fallback() external payable { deposit(); } /** * Implements the WETH9 deposit() function as a no-op. * WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant * deposit and withdraw functions for that use case can be found at L2StandardBridge.sol. * This function allows developers to treat OVM_ETH as WETH without any modifications to their * code. */ function deposit() public payable override { // Calling deposit() with nonzero value will send the ETH to this contract address. // Once received here, we transfer it back by sending to the msg.sender. _transfer(address(this), msg.sender, msg.value); emit Deposit(msg.sender, msg.value); } /** * Implements the WETH9 withdraw() function as a no-op. * WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant * deposit and withdraw functions for that use case can be found at L2StandardBridge.sol. * This function allows developers to treat OVM_ETH as WETH without any modifications to their * code. * @param _wad Amount being withdrawn */ function withdraw( uint256 _wad ) external override { // Calling withdraw() with value exceeding the withdrawer's ovmBALANCE should revert, // as in WETH9. require(balanceOf(msg.sender) >= _wad); // Other than emitting an event, OVM_ETH already is native ETH, so we don't need to do // anything else. emit Withdrawal(msg.sender, _wad); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.8.0; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IL2StandardERC20.sol"; contract L2StandardERC20 is IL2StandardERC20, ERC20 { address public override l1Token; address public l2Bridge; /** * @param _l2Bridge Address of the L2 standard bridge. * @param _l1Token Address of the corresponding L1 token. * @param _name ERC20 name. * @param _symbol ERC20 symbol. */ constructor( address _l2Bridge, address _l1Token, string memory _name, string memory _symbol ) ERC20(_name, _symbol) { l1Token = _l1Token; l2Bridge = _l2Bridge; } modifier onlyL2Bridge { require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn"); _; } function supportsInterface(bytes4 _interfaceId) public override pure returns (bool) { bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165 bytes4 secondSupportedInterface = IL2StandardERC20.l1Token.selector ^ IL2StandardERC20.mint.selector ^ IL2StandardERC20.burn.selector; return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface; } function mint(address _to, uint256 _amount) public virtual override onlyL2Bridge { _mint(_to, _amount); emit Mint(_to, _amount); } function burn(address _from, uint256 _amount) public virtual override onlyL2Bridge { _burn(_from, _amount); emit Burn(_from, _amount); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Interface for WETH9. Also contains the non-ERC20 events /// normally present in the WETH9 implementation. interface IWETH9 is IERC20 { event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; /** * @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 "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { //require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol"; import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol"; import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /* Library Imports */ import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title OVM_L1StandardBridge * @dev The L1 ETH and ERC20 Bridge is a contract which stores deposited L1 funds and standard * tokens that are in use on L2. It synchronizes a corresponding L2 Bridge, informing it of deposits * and listening to it for newly finalized withdrawals. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1StandardBridge is iOVM_L1StandardBridge, OVM_CrossDomainEnabled { using SafeMath for uint; using SafeERC20 for IERC20; /******************************** * External Contract References * ********************************/ address public l2TokenBridge; // Maps L1 token to L2 token to balance of the L1 token deposited mapping(address => mapping (address => uint256)) public deposits; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) {} /****************** * Initialization * ******************/ /** * @param _l1messenger L1 Messenger address being used for cross-chain communications. * @param _l2TokenBridge L2 standard bridge address. */ function initialize( address _l1messenger, address _l2TokenBridge ) public { require(messenger == address(0), "Contract has already been initialized."); messenger = _l1messenger; l2TokenBridge = _l2TokenBridge; } /************** * Depositing * **************/ /** @dev Modifier requiring sender to be EOA. This check could be bypassed by a malicious * contract via initcode, but it takes care of the user error we want to avoid. */ modifier onlyEOA() { // Used to stop deposits from contracts (avoid accidentally lost tokens) require(!Address.isContract(msg.sender), "Account not EOA"); _; } /** * @dev This function can be called with no data * to deposit an amount of ETH to the caller's balance on L2. * Since the receive function doesn't take data, a conservative * default amount is forwarded to L2. */ receive() external payable onlyEOA() { _initiateETHDeposit( msg.sender, msg.sender, 1_300_000, bytes("") ); } /** * @inheritdoc iOVM_L1StandardBridge */ function depositETH( uint32 _l2Gas, bytes calldata _data ) external override payable onlyEOA() { _initiateETHDeposit( msg.sender, msg.sender, _l2Gas, _data ); } /** * @inheritdoc iOVM_L1StandardBridge */ function depositETHTo( address _to, uint32 _l2Gas, bytes calldata _data ) external override payable { _initiateETHDeposit( msg.sender, _to, _l2Gas, _data ); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of * the deposit. * @param _from Account to pull the deposit from on L1. * @param _to Account to give the deposit to on L2. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateETHDeposit( address _from, address _to, uint32 _l2Gas, bytes memory _data ) internal { // Construct calldata for finalizeDeposit call bytes memory message = abi.encodeWithSelector( iOVM_L2ERC20Bridge.finalizeDeposit.selector, address(0), Lib_PredeployAddresses.OVM_ETH, _from, _to, msg.value, _data ); // Send calldata into L2 sendCrossDomainMessage( l2TokenBridge, _l2Gas, message ); emit ETHDepositInitiated(_from, _to, msg.value, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function depositERC20( address _l1Token, address _l2Token, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) external override virtual onlyEOA() { _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _l2Gas, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function depositERC20To( address _l1Token, address _l2Token, address _to, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) external override virtual { _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _l2Gas, _data); } /** * @dev Performs the logic for deposits by informing the L2 Deposited Token * contract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom) * * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 * @param _amount Amount of the ERC20 to deposit. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateERC20Deposit( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) internal { // When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future // withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if // _from is an EOA or address(0). IERC20(_l1Token).safeTransferFrom( _from, address(this), _amount ); // Construct calldata for _l2Token.finalizeDeposit(_to, _amount) bytes memory message = abi.encodeWithSelector( iOVM_L2ERC20Bridge.finalizeDeposit.selector, _l1Token, _l2Token, _from, _to, _amount, _data ); // Send calldata into L2 sendCrossDomainMessage( l2TokenBridge, _l2Gas, message ); deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].add(_amount); emit ERC20DepositInitiated(_l1Token, _l2Token, _from, _to, _amount, _data); } /************************* * Cross-chain Functions * *************************/ /** * @inheritdoc iOVM_L1StandardBridge */ function finalizeETHWithdrawal( address _from, address _to, uint256 _amount, bytes calldata _data ) external override onlyFromCrossDomainAccount(l2TokenBridge) { (bool success, ) = _to.call{value: _amount}(new bytes(0)); require(success, "TransferHelper::safeTransferETH: ETH transfer failed"); emit ETHWithdrawalFinalized(_from, _to, _amount, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function finalizeERC20Withdrawal( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, bytes calldata _data ) external override onlyFromCrossDomainAccount(l2TokenBridge) { deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].sub(_amount); // When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer IERC20(_l1Token).safeTransfer(_to, _amount); emit ERC20WithdrawalFinalized(_l1Token, _l2Token, _from, _to, _amount, _data); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway. * NOTE: This is left for one upgrade only so we are able to receive the migrated ETH from the * old contract */ function donateETH() external payable {} } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol"; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { OVM_ETH } from "../predeploys/OVM_ETH.sol"; /* External Imports */ import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ECDSA } from "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title OVM_ECDSAContractAccount * @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the * ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by * providing EIP155 formatted transaction encodings. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount { /************* * Libraries * *************/ using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx; /************* * Constants * *************/ // TODO: should be the amount sufficient to cover the gas costs of all of the transactions up // to and including the CALL/CREATE which forms the entrypoint of the transaction. uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000; /******************** * Public Functions * ********************/ /** * No-op fallback mirrors behavior of calling an EOA on L1. */ fallback() external payable { return; } /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature( bytes32 hash, bytes memory signature ) public view returns ( bytes4 magicValue ) { return ECDSA.recover(hash, signature) == address(this) ? this.isValidSignature.selector : bytes4(0); } /** * Executes a signed transaction. * @param _transaction Signed EIP155 transaction. * @return Whether or not the call returned (rather than reverted). * @return Data returned by the call. */ function execute( Lib_EIP155Tx.EIP155Tx memory _transaction ) override public returns ( bool, bytes memory ) { // Address of this contract within the ovm (ovmADDRESS) should be the same as the // recovered address of the user who signed this message. This is how we manage to shim // account abstraction even though the user isn't a contract. require( _transaction.sender() == Lib_ExecutionManagerWrapper.ovmADDRESS(), "Signature provided for EOA transaction execution is invalid." ); require( _transaction.chainId == Lib_ExecutionManagerWrapper.ovmCHAINID(), "Transaction signed with wrong chain ID" ); // Need to make sure that the transaction nonce is right. require( _transaction.nonce == Lib_ExecutionManagerWrapper.ovmGETNONCE(), "Transaction nonce does not match the expected nonce." ); // TEMPORARY: Disable gas checks for mainnet. // // Need to make sure that the gas is sufficient to execute the transaction. // require( // gasleft() >= SafeMath.add(transaction.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD), // "Gas is not sufficient to execute the transaction." // ); // Transfer fee to relayer. require( OVM_ETH(Lib_PredeployAddresses.OVM_ETH).transfer( Lib_PredeployAddresses.SEQUENCER_FEE_WALLET, SafeMath.mul(_transaction.gasLimit, _transaction.gasPrice) ), "Fee was not transferred to relayer." ); if (_transaction.isCreate) { // TEMPORARY: Disable value transfer for contract creations. require( _transaction.value == 0, "Value transfer in contract creation not supported." ); (address created, bytes memory revertdata) = Lib_ExecutionManagerWrapper.ovmCREATE( _transaction.data ); // Return true if the contract creation succeeded, false w/ revertdata otherwise. if (created != address(0)) { return (true, abi.encode(created)); } else { return (false, revertdata); } } else { // We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps // the nonce of the calling account. Normally an EOA would bump the nonce for both // cases, but since this is a contract we'd end up bumping the nonce twice. Lib_ExecutionManagerWrapper.ovmINCREMENTNONCE(); // NOTE: Upgrades are temporarily disabled because users can, in theory, modify their // EOA so that they don't have to pay any fees to the sequencer. Function will remain // disabled until a robust solution is in place. require( _transaction.to != Lib_ExecutionManagerWrapper.ovmADDRESS(), "Calls to self are disabled until upgradability is re-enabled." ); return _transaction.to.call{value: _transaction.value}(_transaction.data); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; /** * @title iOVM_ECDSAContractAccount */ interface iOVM_ECDSAContractAccount { /******************** * Public Functions * ********************/ function execute( Lib_EIP155Tx.EIP155Tx memory _transaction ) external returns ( bool, bytes memory ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; /** * @title Lib_EIP155Tx * @dev A simple library for dealing with the transaction type defined by EIP155: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md */ library Lib_EIP155Tx { /*********** * Structs * ***********/ // Struct representing an EIP155 transaction. See EIP link above for more information. struct EIP155Tx { // These fields correspond to the actual RLP-encoded fields specified by EIP155. uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; uint8 v; bytes32 r; bytes32 s; // Chain ID to associate this transaction with. Used all over the place, seemed easier to // set this once when we create the transaction rather than providing it as an input to // each function. I don't see a strong need to have a transaction with a mutable chain ID. uint256 chainId; // The ECDSA "recovery parameter," should always be 0 or 1. EIP155 specifies that: // `v = {0,1} + CHAIN_ID * 2 + 35` // Where `{0,1}` is a stand in for our `recovery_parameter`. Now computing our formula for // the recovery parameter: // 1. `v = {0,1} + CHAIN_ID * 2 + 35` // 2. `v = recovery_parameter + CHAIN_ID * 2 + 35` // 3. `v - CHAIN_ID * 2 - 35 = recovery_parameter` // So we're left with the final formula: // `recovery_parameter = v - CHAIN_ID * 2 - 35` // NOTE: This variable is a uint8 because `v` is inherently limited to a uint8. If we // didn't use a uint8, then recovery_parameter would always be a negative number for chain // IDs greater than 110 (`255 - 110 * 2 - 35 = 0`). So we need to wrap around to support // anything larger. uint8 recoveryParam; // Whether or not the transaction is a creation. Necessary because we can't make an address // "nil". Using the zero address creates a potential conflict if the user did actually // intend to send a transaction to the zero address. bool isCreate; } // Lets us use nicer syntax. using Lib_EIP155Tx for EIP155Tx; /********************** * Internal Functions * **********************/ /** * Decodes an EIP155 transaction and attaches a given Chain ID. * Transaction *must* be RLP-encoded. * @param _encoded RLP-encoded EIP155 transaction. * @param _chainId Chain ID to assocaite with this transaction. * @return Parsed transaction. */ function decode( bytes memory _encoded, uint256 _chainId ) internal pure returns ( EIP155Tx memory ) { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_encoded); // Note formula above about how recoveryParam is computed. uint8 v = uint8(Lib_RLPReader.readUint256(decoded[6])); uint8 recoveryParam = uint8(v - 2 * _chainId - 35); // Recovery param being anything other than 0 or 1 indicates that we have the wrong chain // ID. require( recoveryParam < 2, "Lib_EIP155Tx: Transaction signed with wrong chain ID" ); // Creations can be detected by looking at the byte length here. bool isCreate = Lib_RLPReader.readBytes(decoded[3]).length == 0; return EIP155Tx({ nonce: Lib_RLPReader.readUint256(decoded[0]), gasPrice: Lib_RLPReader.readUint256(decoded[1]), gasLimit: Lib_RLPReader.readUint256(decoded[2]), to: Lib_RLPReader.readAddress(decoded[3]), value: Lib_RLPReader.readUint256(decoded[4]), data: Lib_RLPReader.readBytes(decoded[5]), v: v, r: Lib_RLPReader.readBytes32(decoded[7]), s: Lib_RLPReader.readBytes32(decoded[8]), chainId: _chainId, recoveryParam: recoveryParam, isCreate: isCreate }); } /** * Encodes an EIP155 transaction into RLP. * @param _transaction EIP155 transaction to encode. * @param _includeSignature Whether or not to encode the signature. * @return RLP-encoded transaction. */ function encode( EIP155Tx memory _transaction, bool _includeSignature ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](9); raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce); raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice); raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit); // We write the encoding of empty bytes when the transaction is a creation, *not* the zero // address as one might assume. if (_transaction.isCreate) { raw[3] = Lib_RLPWriter.writeBytes(""); } else { raw[3] = Lib_RLPWriter.writeAddress(_transaction.to); } raw[4] = Lib_RLPWriter.writeUint(_transaction.value); raw[5] = Lib_RLPWriter.writeBytes(_transaction.data); if (_includeSignature) { raw[6] = Lib_RLPWriter.writeUint(_transaction.v); raw[7] = Lib_RLPWriter.writeBytes32(_transaction.r); raw[8] = Lib_RLPWriter.writeBytes32(_transaction.s); } else { // Chain ID *is* included in the unsigned transaction. raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId); raw[7] = Lib_RLPWriter.writeBytes(""); raw[8] = Lib_RLPWriter.writeBytes(""); } return Lib_RLPWriter.writeList(raw); } /** * Computes the hash of an EIP155 transaction. Assumes that you don't want to include the * signature in this hash because that's a very uncommon usecase. If you really want to include * the signature, just encode with the signature and take the hash yourself. */ function hash( EIP155Tx memory _transaction ) internal pure returns ( bytes32 ) { return keccak256( _transaction.encode(false) ); } /** * Computes the sender of an EIP155 transaction. * @param _transaction EIP155 transaction to get a sender for. * @return Address corresponding to the private key that signed this transaction. */ function sender( EIP155Tx memory _transaction ) internal pure returns ( address ) { return ecrecover( _transaction.hash(), _transaction.recoveryParam + 27, _transaction.r, _transaction.s ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; import { Lib_PredeployAddresses } from "../constants/Lib_PredeployAddresses.sol"; /** * @title Lib_ExecutionManagerWrapper * @dev This library acts as a utility for easily calling the OVM_ExecutionManagerWrapper, the * predeployed contract which exposes the `kall` builtin. Effectively, this contract allows the * user to trigger OVM opcodes by directly calling the OVM_ExecutionManger. * * Compiler used: solc * Runtime target: OVM */ library Lib_ExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCREATE call. * @param _bytecode Code for the new contract. * @return Address of the created contract. */ function ovmCREATE( bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmGETNONCE call. * @return Result of calling ovmGETNONCE. */ function ovmGETNONCE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function ovmINCREMENTNONCE() internal { _callWrapperContract( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _callWrapperContract( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Calls the ovmL1TXORIGIN opcode. * @return Address that sent this message from L1. */ function ovmL1TXORIGIN() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmL1TXORIGIN()" ) ); return abi.decode(returndata, (address)); } /** * Calls the ovmCHAINID opcode. * @return Chain ID of the current network. */ function ovmCHAINID() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmADDRESS call. * @return Result of calling ovmADDRESS. */ function ovmADDRESS() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Calls the value-enabled ovmCALL opcode. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) internal returns ( bool, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALL(uint256,address,uint256,bytes)", _gasLimit, _address, _value, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Calls the ovmBALANCE opcode. * @param _address OVM account to query the balance of. * @return Balance of the account. */ function ovmBALANCE( address _address ) internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmBALANCE(address)", _address ) ); return abi.decode(returndata, (uint256)); } /** * Calls the ovmCALLVALUE opcode. * @return Value of the current call frame. */ function ovmCALLVALUE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALLVALUE()" ) ); return abi.decode(returndata, (uint256)); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return Data sent back by the OVM_ExecutionManager. */ function _callWrapperContract( bytes memory _calldata ) private returns ( bytes memory ) { (bool success, bytes memory returndata) = Lib_PredeployAddresses.EXECUTION_MANAGER_WRAPPER.delegatecall(_calldata); if (success == true) { return returndata; } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem( bytes memory _in ) internal pure returns ( RLPItem memory ) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( RLPItem memory _in ) internal pure returns ( RLPItem[] memory ) { ( uint256 listOffset, , RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value." ); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length." ); ( uint256 itemOffset, uint256 itemLength, ) = _decodeLength(RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( bytes memory _in ) internal pure returns ( RLPItem[] memory ) { return readList( toRLPItem(_in) ); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value." ); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( bytes memory _in ) internal pure returns ( bytes memory ) { return readBytes( toRLPItem(_in) ); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( RLPItem memory _in ) internal pure returns ( string memory ) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( bytes memory _in ) internal pure returns ( string memory ) { return readString( toRLPItem(_in) ); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( RLPItem memory _in ) internal pure returns ( bytes32 ) { require( _in.length <= 33, "Invalid RLP bytes32 value." ); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value." ); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( bytes memory _in ) internal pure returns ( bytes32 ) { return readBytes32( toRLPItem(_in) ); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( RLPItem memory _in ) internal pure returns ( uint256 ) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( bytes memory _in ) internal pure returns ( uint256 ) { return readUint256( toRLPItem(_in) ); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( RLPItem memory _in ) internal pure returns ( bool ) { require( _in.length == 1, "Invalid RLP boolean value." ); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1" ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( RLPItem memory _in ) internal pure returns ( address ) { if (_in.length == 1) { return address(0); } require( _in.length == 21, "Invalid RLP address value." ); return address(readUint256(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( bytes memory _in ) internal pure returns ( address ) { return readAddress( toRLPItem(_in) ); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength( RLPItem memory _in ) private pure returns ( uint256, uint256, RLPItemType ) { require( _in.length > 0, "RLP item cannot be null." ); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require( _in.length > strLen, "Invalid RLP short string." ); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require( _in.length > lenOfStrLen, "Invalid RLP long string length." ); uint256 strLen; assembly { // Pick out the string length. strLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)) ) } require( _in.length > lenOfStrLen + strLen, "Invalid RLP long string." ); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require( _in.length > listLen, "Invalid RLP short list." ); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require( _in.length > lenOfListLen, "Invalid RLP long list length." ); uint256 listLen; assembly { // Pick out the list length. listLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)) ) } require( _in.length > lenOfListLen + listLen, "Invalid RLP long list." ); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns ( bytes memory ) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory ) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a bytes32 value. * @param _in The bytes32 to encode. * @return _out The RLP encoded bytes32 in bytes. */ function writeBytes32( bytes32 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory ) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory ) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_ErrorUtils */ library Lib_ErrorUtils { /********************** * Internal Functions * **********************/ /** * Encodes an error string into raw solidity-style revert data. * (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))")) * Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string) * #panic-via-assert-and-error-via-require * @param _reason Reason for the reversion. * @return Standard solidity revert data for the given reason. */ function encodeRevertString( string memory _reason ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "Error(string)", _reason ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; /** * @title OVM_ProxyEOA * @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation * contract. In combination with the logic implemented in the ECDSA Contract Account, this enables * a form of upgradable 'account abstraction' on layer 2. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ProxyEOA { /********** * Events * **********/ event Upgraded( address indexed implementation ); /************* * Constants * *************/ // solhint-disable-next-line max-line-length bytes32 constant IMPLEMENTATION_KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; //bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1); /********************* * Fallback Function * *********************/ fallback() external payable { (bool success, bytes memory returndata) = getImplementation().delegatecall(msg.data); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } // WARNING: We use the deployed bytecode of this contract as a template to create ProxyEOA // contracts. As a result, we must *not* perform any constructor logic. Use initialization // functions if necessary. /******************** * Public Functions * ********************/ /** * Changes the implementation address. * @param _implementation New implementation address. */ function upgrade( address _implementation ) external { require( msg.sender == Lib_ExecutionManagerWrapper.ovmADDRESS(), "EOAs can only upgrade their own EOA implementation." ); _setImplementation(_implementation); emit Upgraded(_implementation); } /** * Gets the address of the current implementation. * @return Current implementation address. */ function getImplementation() public view returns ( address ) { bytes32 addr32; assembly { addr32 := sload(IMPLEMENTATION_KEY) } address implementation = Lib_Bytes32Utils.toAddress(addr32); if (implementation == address(0)) { return Lib_PredeployAddresses.ECDSA_CONTRACT_ACCOUNT; } else { return implementation; } } /********************** * Internal Functions * **********************/ function _setImplementation( address _implementation ) internal { bytes32 addr32 = Lib_Bytes32Utils.fromAddress(_implementation); assembly { sstore(IMPLEMENTATION_KEY, addr32) } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool( bytes32 _in ) internal pure returns ( bool ) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool( bool _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress( bytes32 _in ) internal pure returns ( address ) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress( address _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol"; /** * @title OVM_SequencerEntrypoint * @dev The Sequencer Entrypoint is a predeploy which, despite its name, can in fact be called by * any account. It accepts a more efficient compressed calldata format, which it decompresses and * encodes to the standard EIP155 transaction format. * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_SequencerEntrypoint { /************* * Libraries * *************/ using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx; /********************* * Fallback Function * *********************/ /** * Expects an RLP-encoded EIP155 transaction as input. See the EIP for a more detailed * description of this transaction format: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md */ fallback() external { // We use this twice, so it's more gas efficient to store a copy of it (barely). bytes memory encodedTx = msg.data; // Decode the tx with the correct chain ID. Lib_EIP155Tx.EIP155Tx memory transaction = Lib_EIP155Tx.decode( encodedTx, Lib_ExecutionManagerWrapper.ovmCHAINID() ); // Value is computed on the fly. Keep it in the stack to save some gas. address target = transaction.sender(); bool isEmptyContract; assembly { isEmptyContract := iszero(extcodesize(target)) } // If the account is empty, deploy the default EOA to that address. if (isEmptyContract) { Lib_ExecutionManagerWrapper.ovmCREATEEOA( transaction.hash(), transaction.recoveryParam, transaction.r, transaction.s ); } // Forward the transaction over to the EOA. (bool success, bytes memory returndata) = target.call( abi.encodeWithSelector(iOVM_ECDSAContractAccount.execute.selector, transaction) ); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../optimistic-ethereum/libraries/codec/Lib_EIP155Tx.sol"; /** * @title TestLib_EIP155Tx */ contract TestLib_EIP155Tx { function decode( bytes memory _encoded, uint256 _chainId ) public pure returns ( Lib_EIP155Tx.EIP155Tx memory ) { return Lib_EIP155Tx.decode( _encoded, _chainId ); } function encode( Lib_EIP155Tx.EIP155Tx memory _transaction, bool _includeSignature ) public pure returns ( bytes memory ) { return Lib_EIP155Tx.encode( _transaction, _includeSignature ); } function hash( Lib_EIP155Tx.EIP155Tx memory _transaction ) public pure returns ( bytes32 ) { return Lib_EIP155Tx.hash( _transaction ); } function sender( Lib_EIP155Tx.EIP155Tx memory _transaction ) public pure returns ( address ) { return Lib_EIP155Tx.sender( _transaction ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol"; import { TestERC20 } from "../../test-helpers/TestERC20.sol"; /** * @title TestLib_RLPWriter */ contract TestLib_RLPWriter { function writeBytes( bytes memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeBytes(_in); } function writeList( bytes[] memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeList(_in); } function writeString( string memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeString(_in); } function writeAddress( address _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeAddress(_in); } function writeUint( uint256 _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeUint(_in); } function writeBool( bool _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeBool(_in); } function writeAddressWithTaintedMemory( address _in ) public returns ( bytes memory _out ) { new TestERC20(); return Lib_RLPWriter.writeAddress(_in); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; // a test ERC20 token with an open mint function contract TestERC20 { using SafeMath for uint; string public constant name = 'Test'; string public constant symbol = 'TST'; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); constructor() {} function mint(address to, uint256 value) public { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _approve(address owner, address spender, uint256 value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint256 value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } library SafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_BytesUtils } from "../../optimistic-ethereum/libraries/utils/Lib_BytesUtils.sol"; import { TestERC20 } from "../../test-helpers/TestERC20.sol"; /** * @title TestLib_BytesUtils */ contract TestLib_BytesUtils { function concat( bytes memory _preBytes, bytes memory _postBytes ) public pure returns (bytes memory) { return abi.encodePacked( _preBytes, _postBytes ); } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) public pure returns (bytes memory) { return Lib_BytesUtils.slice( _bytes, _start, _length ); } function toBytes32( bytes memory _bytes ) public pure returns (bytes32) { return Lib_BytesUtils.toBytes32( _bytes ); } function toUint256( bytes memory _bytes ) public pure returns (uint256) { return Lib_BytesUtils.toUint256( _bytes ); } function toNibbles( bytes memory _bytes ) public pure returns (bytes memory) { return Lib_BytesUtils.toNibbles( _bytes ); } function fromNibbles( bytes memory _bytes ) public pure returns (bytes memory) { return Lib_BytesUtils.fromNibbles( _bytes ); } function equal( bytes memory _bytes, bytes memory _other ) public pure returns (bool) { return Lib_BytesUtils.equal( _bytes, _other ); } function sliceWithTaintedMemory( bytes memory _bytes, uint256 _start, uint256 _length ) public returns (bytes memory) { new TestERC20(); return Lib_BytesUtils.slice( _bytes, _start, _length ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns ( bytes memory ) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice( bytes memory _bytes, uint256 _start ) internal pure returns ( bytes memory ) { if (_start >= _bytes.length) { return bytes(""); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns ( bytes32 ) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } function toBytes32( bytes memory _bytes ) internal pure returns ( bytes32 ) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes } function toUint256( bytes memory _bytes ) internal pure returns ( uint256 ) { return uint256(toBytes32(_bytes)); } function 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; } function toUint8( bytes memory _bytes, uint256 _start ) internal pure returns ( uint8 ) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } 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 toNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns ( bool ) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol"; import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol"; import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol"; import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol"; /* Contract Imports */ import { Abs_FraudContributor } from "./Abs_FraudContributor.sol"; /** * @title OVM_StateTransitioner * @dev The State Transitioner coordinates the execution of a state transition during the evaluation * of a fraud proof. It feeds verified input to the Execution Manager's run(), and controls a * State Manager (which is uniquely created for each fraud proof). * Once a fraud proof has been initialized, this contract is provided with the pre-state root and * verifies that the OVM storage slots committed to the State Mangager are contained in that state * This contract controls the State Manager and Execution Manager, and uses them to calculate the * post-state root by applying the transaction. The Fraud Verifier can then check for fraud by * comparing the calculated post-state root with the proposed post-state root. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner { /******************* * Data Structures * *******************/ enum TransitionPhase { PRE_EXECUTION, POST_EXECUTION, COMPLETE } /******************************************* * Contract Variables: Contract References * *******************************************/ iOVM_StateManager public ovmStateManager; /******************************************* * Contract Variables: Internal Accounting * *******************************************/ bytes32 internal preStateRoot; bytes32 internal postStateRoot; TransitionPhase public phase; uint256 internal stateTransitionIndex; bytes32 internal transactionHash; /************* * Constants * *************/ // solhint-disable-next-line max-line-length bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line max-line-length bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. * @param _stateTransitionIndex Index of the state transition being verified. * @param _preStateRoot State root before the transition was executed. * @param _transactionHash Hash of the executed transaction. */ constructor( address _libAddressManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) Lib_AddressResolver(_libAddressManager) { stateTransitionIndex = _stateTransitionIndex; preStateRoot = _preStateRoot; postStateRoot = _preStateRoot; transactionHash = _transactionHash; ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory")) .create(address(this)); } /********************** * Function Modifiers * **********************/ /** * Checks that a function is only run during a specific phase. * @param _phase Phase the function must run within. */ modifier onlyDuringPhase( TransitionPhase _phase ) { require( phase == _phase, "Function must be called during the correct phase." ); _; } /********************************** * Public Functions: State Access * **********************************/ /** * Retrieves the state root before execution. * @return _preStateRoot State root before execution. */ function getPreStateRoot() override external view returns ( bytes32 _preStateRoot ) { return preStateRoot; } /** * Retrieves the state root after execution. * @return _postStateRoot State root after execution. */ function getPostStateRoot() override external view returns ( bytes32 _postStateRoot ) { return postStateRoot; } /** * Checks whether the transitioner is complete. * @return _complete Whether or not the transition process is finished. */ function isComplete() override external view returns ( bool _complete ) { return phase == TransitionPhase.COMPLETE; } /*********************************** * Public Functions: Pre-Execution * ***********************************/ /** * Allows a user to prove the initial state of a contract. * @param _ovmContractAddress Address of the contract on the OVM. * @param _ethContractAddress Address of the corresponding contract on L1. * @param _stateTrieWitness Proof of the account state. */ function proveContractState( address _ovmContractAddress, address _ethContractAddress, bytes memory _stateTrieWitness ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { // Exit quickly to avoid unnecessary work. require( ( ovmStateManager.hasAccount(_ovmContractAddress) == false && ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false ), "Account state has already been proven." ); // Function will fail if the proof is not a valid inclusion or exclusion proof. ( bool exists, bytes memory encodedAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(_ovmContractAddress), _stateTrieWitness, preStateRoot ); if (exists == true) { // Account exists, this was an inclusion proof. Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedAccount ); address ethContractAddress = _ethContractAddress; if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) { // Use a known empty contract to prevent an attack in which a user provides a // contract address here and then later deploys code to it. ethContractAddress = 0x0000000000000000000000000000000000000000; } else { // Otherwise, make sure that the code at the provided eth address matches the hash // of the code stored on L2. require( Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash, // solhint-disable-next-line max-line-length "OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash." ); } ovmStateManager.putAccount( _ovmContractAddress, Lib_OVMCodec.Account({ nonce: account.nonce, balance: account.balance, storageRoot: account.storageRoot, codeHash: account.codeHash, ethAddress: ethContractAddress, isFresh: false }) ); } else { // Account does not exist, this was an exclusion proof. ovmStateManager.putEmptyAccount(_ovmContractAddress); } } /** * Allows a user to prove the initial state of a contract storage slot. * @param _ovmContractAddress Address of the contract on the OVM. * @param _key Claimed account slot key. * @param _storageTrieWitness Proof of the storage slot. */ function proveStorageSlot( address _ovmContractAddress, bytes32 _key, bytes memory _storageTrieWitness ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { // Exit quickly to avoid unnecessary work. require( ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false, "Storage slot has already been proven." ); require( ovmStateManager.hasAccount(_ovmContractAddress) == true, "Contract must be verified before proving a storage slot." ); bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress); bytes32 value; if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) { // Storage trie was empty, so the user is always allowed to insert zero-byte values. value = bytes32(0); } else { // Function will fail if the proof is not a valid inclusion or exclusion proof. ( bool exists, bytes memory encodedValue ) = Lib_SecureMerkleTrie.get( abi.encodePacked(_key), _storageTrieWitness, storageRoot ); if (exists == true) { // Inclusion proof. // Stored values are RLP encoded, with leading zeros removed. value = Lib_BytesUtils.toBytes32PadLeft( Lib_RLPReader.readBytes(encodedValue) ); } else { // Exclusion proof, can only be zero bytes. value = bytes32(0); } } ovmStateManager.putContractStorage( _ovmContractAddress, _key, value ); } /******************************* * Public Functions: Execution * *******************************/ /** * Executes the state transition. * @param _transaction OVM transaction to execute. */ function applyTransaction( Lib_OVMCodec.Transaction memory _transaction ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( Lib_OVMCodec.hashTransaction(_transaction) == transactionHash, "Invalid transaction provided." ); // We require gas to complete the logic here in run() before/after execution, // But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism) // This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first // going into EM, then going into the code contract). require( // 1032/1000 = 1.032 = (64/63)^2 rounded up gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000, "Not enough gas to execute transaction deterministically." ); iOVM_ExecutionManager ovmExecutionManager = iOVM_ExecutionManager(resolve("OVM_ExecutionManager")); // We call `setExecutionManager` right before `run` (and not earlier) just in case the // OVM_ExecutionManager address was updated between the time when this contract was created // and when `applyTransaction` was called. ovmStateManager.setExecutionManager(address(ovmExecutionManager)); // `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction` // or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line // if that's the case. ovmExecutionManager.run(_transaction, address(ovmStateManager)); // Prevent the Execution Manager from calling this SM again. ovmStateManager.setExecutionManager(address(0)); phase = TransitionPhase.POST_EXECUTION; } /************************************ * Public Functions: Post-Execution * ************************************/ /** * Allows a user to commit the final state of a contract. * @param _ovmContractAddress Address of the contract on the OVM. * @param _stateTrieWitness Proof of the account state. */ function commitContractState( address _ovmContractAddress, bytes memory _stateTrieWitness ) override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( ovmStateManager.getTotalUncommittedContractStorage() == 0, "All storage must be committed before committing account states." ); require ( ovmStateManager.commitAccount(_ovmContractAddress) == true, "Account state wasn't changed or has already been committed." ); Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress); postStateRoot = Lib_SecureMerkleTrie.update( abi.encodePacked(_ovmContractAddress), Lib_OVMCodec.encodeEVMAccount( Lib_OVMCodec.toEVMAccount(account) ), _stateTrieWitness, postStateRoot ); // Emit an event to help clients figure out the proof ordering. emit AccountCommitted( _ovmContractAddress ); } /** * Allows a user to commit the final state of a contract storage slot. * @param _ovmContractAddress Address of the contract on the OVM. * @param _key Claimed account slot key. * @param _storageTrieWitness Proof of the storage slot. */ function commitStorageSlot( address _ovmContractAddress, bytes32 _key, bytes memory _storageTrieWitness ) override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true, "Storage slot value wasn't changed or has already been committed." ); Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress); bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key); account.storageRoot = Lib_SecureMerkleTrie.update( abi.encodePacked(_key), Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros(value) ), _storageTrieWitness, account.storageRoot ); ovmStateManager.putAccount(_ovmContractAddress, account); // Emit an event to help clients figure out the proof ordering. emit ContractStorageCommitted( _ovmContractAddress, _key ); } /********************************** * Public Functions: Finalization * **********************************/ /** * Finalizes the transition process. */ function completeTransition() override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) { require( ovmStateManager.getTotalUncommittedAccounts() == 0, "All accounts must be committed before completing a transition." ); require( ovmStateManager.getTotalUncommittedContractStorage() == 0, "All storage must be committed before completing a transition." ); phase = TransitionPhase.COMPLETE; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction( Transaction memory _transaction ) internal pure returns ( bytes memory ) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction( Transaction memory _transaction ) internal pure returns ( bytes32 ) { return keccak256(encodeTransaction(_transaction)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve( string memory _name ) public view returns ( address ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol"; /** * @title Lib_EthUtils */ library Lib_EthUtils { /********************** * Internal Functions * **********************/ /** * Gets the code for a given address. * @param _address Address to get code for. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Code read from the contract. */ function getCode( address _address, uint256 _offset, uint256 _length ) internal view returns ( bytes memory ) { bytes memory code; assembly { code := mload(0x40) mstore(0x40, add(code, add(_length, 0x20))) mstore(code, _length) extcodecopy(_address, add(code, 0x20), _offset, _length) } return code; } /** * Gets the full code for a given address. * @param _address Address to get code for. * @return Full code of the contract. */ function getCode( address _address ) internal view returns ( bytes memory ) { return getCode( _address, 0, getCodeSize(_address) ); } /** * Gets the size of a contract's code in bytes. * @param _address Address to get code size for. * @return Size of the contract's code in bytes. */ function getCodeSize( address _address ) internal view returns ( uint256 ) { uint256 codeSize; assembly { codeSize := extcodesize(_address) } return codeSize; } /** * Gets the hash of a contract's code. * @param _address Address to get a code hash for. * @return Hash of the contract's code. */ function getCodeHash( address _address ) internal view returns ( bytes32 ) { bytes32 codeHash; assembly { codeHash := extcodehash(_address) } return codeHash; } /** * Creates a contract with some given initialization code. * @param _code Contract initialization code. * @return Address of the created contract. */ function createContract( bytes memory _code ) internal returns ( address ) { address created; assembly { created := create( 0, add(_code, 0x20), mload(_code) ) } return created; } /** * Computes the address that would be generated by CREATE. * @param _creator Address creating the contract. * @param _nonce Creator's nonce. * @return Address to be generated by CREATE. */ function getAddressForCREATE( address _creator, uint256 _nonce ) internal pure returns ( address ) { bytes[] memory encoded = new bytes[](2); encoded[0] = Lib_RLPWriter.writeAddress(_creator); encoded[1] = Lib_RLPWriter.writeUint(_nonce); bytes memory encodedList = Lib_RLPWriter.writeList(encoded); return Lib_Bytes32Utils.toAddress(keccak256(encodedList)); } /** * Computes the address that would be generated by CREATE2. * @param _creator Address creating the contract. * @param _bytecode Bytecode of the contract to be created. * @param _salt 32 byte salt value mixed into the hash. * @return Address to be generated by CREATE2. */ function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) internal pure returns ( address ) { bytes32 hashedData = keccak256(abi.encodePacked( byte(0xff), _creator, _salt, keccak256(_bytecode) )); return Lib_Bytes32Utils.toAddress(hashedData); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol"; /** * @title Lib_SecureMerkleTrie */ library Lib_SecureMerkleTrie { /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.update(key, _value, _proof, _root); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.get(key, _proof, _root); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.getSingleNodeRootHash(key, _value); } /********************* * Private Functions * *********************/ /** * Computes the secure counterpart to a key. * @param _key Key to get a secure key from. * @return _secureKey Secure version of the key. */ function _getSecureKey( bytes memory _key ) private pure returns ( bytes memory _secureKey ) { return abi.encodePacked(keccak256(_key)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateTransitioner */ interface iOVM_StateTransitioner { /********** * Events * **********/ event AccountCommitted( address _address ); event ContractStorageCommitted( address _address, bytes32 _key ); /********************************** * Public Functions: State Access * **********************************/ function getPreStateRoot() external view returns (bytes32 _preStateRoot); function getPostStateRoot() external view returns (bytes32 _postStateRoot); function isComplete() external view returns (bool _complete); /*********************************** * Public Functions: Pre-Execution * ***********************************/ function proveContractState( address _ovmContractAddress, address _ethContractAddress, bytes calldata _stateTrieWitness ) external; function proveStorageSlot( address _ovmContractAddress, bytes32 _key, bytes calldata _storageTrieWitness ) external; /******************************* * Public Functions: Execution * *******************************/ function applyTransaction( Lib_OVMCodec.Transaction calldata _transaction ) external; /************************************ * Public Functions: Post-Execution * ************************************/ function commitContractState( address _ovmContractAddress, bytes calldata _stateTrieWitness ) external; function commitStorageSlot( address _ovmContractAddress, bytes32 _key, bytes calldata _storageTrieWitness ) external; /********************************** * Public Functions: Finalization * **********************************/ function completeTransition() external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; interface ERC20 { function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); } /// All the errors which may be encountered on the bond manager library Errors { string constant ERC20_ERR = "BondManager: Could not post bond"; // solhint-disable-next-line max-line-length string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized"; string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed"; string constant WRONG_STATE = "BondManager: Wrong bond state for proposer"; string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first"; string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending"; string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal"; // solhint-disable-next-line max-line-length string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function"; // solhint-disable-next-line max-line-length string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function"; // solhint-disable-next-line max-line-length string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function"; string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes"; } /** * @title iOVM_BondManager */ interface iOVM_BondManager { /******************* * Data Structures * *******************/ /// The lifecycle of a proposer's bond enum State { // Before depositing or after getting slashed, a user is uncollateralized NOT_COLLATERALIZED, // After depositing, a user is collateralized COLLATERALIZED, // After a user has initiated a withdrawal WITHDRAWING } /// A bond posted by a proposer struct Bond { // The user's state State state; // The timestamp at which a proposer issued their withdrawal request uint32 withdrawalTimestamp; // The time when the first disputed was initiated for this bond uint256 firstDisputeAt; // The earliest observed state root for this bond which has had fraud bytes32 earliestDisputedStateRoot; // The state root's timestamp uint256 earliestTimestamp; } // Per pre-state root, store the number of state provisions that were made // and how many of these calls were made by each user. Payouts will then be // claimed by users proportionally for that dispute. struct Rewards { // Flag to check if rewards for a fraud proof are claimable bool canClaim; // Total number of `recordGasSpent` calls made uint256 total; // The gas spent by each user to provide witness data. The sum of all // values inside this map MUST be equal to the value of `total` mapping(address => uint256) gasSpent; } /******************** * Public Functions * ********************/ function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) external; function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) external; function deposit() external; function startWithdrawal() external; function finalizeWithdrawal() external; function claim( address _who ) external; function isCollateralized( address _who ) external view returns (bool); function getGasSpent( bytes32 _preStateRoot, address _who ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; interface iOVM_ExecutionManager { /********** * Enums * *********/ enum RevertFlag { OUT_OF_GAS, INTENTIONAL_REVERT, EXCEEDS_NUISANCE_GAS, INVALID_STATE_ACCESS, UNSAFE_BYTECODE, CREATE_COLLISION, STATIC_VIOLATION, CREATOR_NOT_ALLOWED } enum GasMetadataKey { CURRENT_EPOCH_START_TIMESTAMP, CUMULATIVE_SEQUENCER_QUEUE_GAS, CUMULATIVE_L1TOL2_QUEUE_GAS, PREV_EPOCH_SEQUENCER_QUEUE_GAS, PREV_EPOCH_L1TOL2_QUEUE_GAS } enum MessageType { ovmCALL, ovmSTATICCALL, ovmDELEGATECALL, ovmCREATE, ovmCREATE2 } /*********** * Structs * ***********/ struct GasMeterConfig { uint256 minTransactionGasLimit; uint256 maxTransactionGasLimit; uint256 maxGasPerQueuePerEpoch; uint256 secondsPerEpoch; } struct GlobalContext { uint256 ovmCHAINID; } struct TransactionContext { Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN; uint256 ovmTIMESTAMP; uint256 ovmNUMBER; uint256 ovmGASLIMIT; uint256 ovmTXGASLIMIT; address ovmL1TXORIGIN; } struct TransactionRecord { uint256 ovmGasRefund; } struct MessageContext { address ovmCALLER; address ovmADDRESS; uint256 ovmCALLVALUE; bool isStatic; } struct MessageRecord { uint256 nuisanceGasLeft; } /************************************ * Transaction Execution Entrypoint * ************************************/ function run( Lib_OVMCodec.Transaction calldata _transaction, address _txStateManager ) external returns (bytes memory); /******************* * Context Opcodes * *******************/ function ovmCALLER() external view returns (address _caller); function ovmADDRESS() external view returns (address _address); function ovmCALLVALUE() external view returns (uint _callValue); function ovmTIMESTAMP() external view returns (uint256 _timestamp); function ovmNUMBER() external view returns (uint256 _number); function ovmGASLIMIT() external view returns (uint256 _gasLimit); function ovmCHAINID() external view returns (uint256 _chainId); /********************** * L2 Context Opcodes * **********************/ function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin); function ovmL1TXORIGIN() external view returns (address _l1TxOrigin); /******************* * Halting Opcodes * *******************/ function ovmREVERT(bytes memory _data) external; /***************************** * Contract Creation Opcodes * *****************************/ function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata); function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata); /******************************* * Account Abstraction Opcodes * ******************************/ function ovmGETNONCE() external returns (uint256 _nonce); function ovmINCREMENTNONCE() external; function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external; /**************************** * Contract Calling Opcodes * ****************************/ // Valueless ovmCALL for maintaining backwards compatibility with legacy OVM bytecode. function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmCALL(uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); /**************************** * Contract Storage Opcodes * ****************************/ function ovmSLOAD(bytes32 _key) external returns (bytes32 _value); function ovmSSTORE(bytes32 _key, bytes32 _value) external; /************************* * Contract Code Opcodes * *************************/ function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code); function ovmEXTCODESIZE(address _contract) external returns (uint256 _size); function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash); /********************* * ETH Value Opcodes * *********************/ function ovmBALANCE(address _contract) external returns (uint256 _balance); function ovmSELFBALANCE() external returns (uint256 _balance); /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateManager */ interface iOVM_StateManager { /******************* * Data Structures * *******************/ enum ItemState { ITEM_UNTOUCHED, ITEM_LOADED, ITEM_CHANGED, ITEM_COMMITTED } /*************************** * Public Functions: Misc * ***************************/ function isAuthenticated(address _address) external view returns (bool); /*************************** * Public Functions: Setup * ***************************/ function owner() external view returns (address _owner); function ovmExecutionManager() external view returns (address _ovmExecutionManager); function setExecutionManager(address _ovmExecutionManager) external; /************************************ * Public Functions: Account Access * ************************************/ function putAccount(address _address, Lib_OVMCodec.Account memory _account) external; function putEmptyAccount(address _address) external; function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account); function hasAccount(address _address) external view returns (bool _exists); function hasEmptyAccount(address _address) external view returns (bool _exists); function setAccountNonce(address _address, uint256 _nonce) external; function getAccountNonce(address _address) external view returns (uint256 _nonce); function getAccountEthAddress(address _address) external view returns (address _ethAddress); function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot); function initPendingAccount(address _address) external; function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external; function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded); function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged); function commitAccount(address _address) external returns (bool _wasAccountCommitted); function incrementTotalUncommittedAccounts() external; function getTotalUncommittedAccounts() external view returns (uint256 _total); function wasAccountChanged(address _address) external view returns (bool); function wasAccountCommitted(address _address) external view returns (bool); /************************************ * Public Functions: Storage Access * ************************************/ function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external; function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value); function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists); function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded); function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged); function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted); function incrementTotalUncommittedContractStorage() external; function getTotalUncommittedContractStorage() external view returns (uint256 _total); function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool); function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { iOVM_StateManager } from "./iOVM_StateManager.sol"; /** * @title iOVM_StateManagerFactory */ interface iOVM_StateManagerFactory { /*************************************** * Public Functions: Contract Creation * ***************************************/ function create( address _owner ) external returns ( iOVM_StateManager _ovmStateManager ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /// Minimal contract to be inherited by contracts consumed by users that provide /// data for fraud proofs abstract contract Abs_FraudContributor is Lib_AddressResolver { /// Decorate your functions with this modifier to store how much total gas was /// consumed by the sender, to reward users fairly modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) { uint256 startGas = gasleft(); _; uint256 gasSpent = startGas - gasleft(); iOVM_BondManager(resolve("OVM_BondManager")) .recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string indexed _name, address _newAddress, address _oldAddress ); /************* * Variables * *************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet( _name, _address, oldAddress ); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress( string memory _name ) external view returns ( address ) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash( string memory _name ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.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.5.0 <0.8.0; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; /** * @title Lib_MerkleTrie */ library Lib_MerkleTrie { /******************* * Data Structures * *******************/ enum NodeType { BranchNode, ExtensionNode, LeafNode } struct TrieNode { bytes encoded; Lib_RLPReader.RLPItem[] decoded; } /********************** * Contract Constants * **********************/ // TREE_RADIX determines the number of elements per branch node. uint256 constant TREE_RADIX = 16; // Branch nodes have TREE_RADIX elements plus an additional `value` slot. uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1; // Leaf nodes and extension nodes always have two elements, a `path` and a `value`. uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2; // Prefixes are prepended to the `path` within a leaf or extension node and // allow us to differentiate between the two node types. `ODD` or `EVEN` is // determined by the number of nibbles within the unprefixed `path`. If the // number of nibbles if even, we need to insert an extra padding nibble so // the resulting prefixed `path` has an even number of nibbles. uint8 constant PREFIX_EXTENSION_EVEN = 0; uint8 constant PREFIX_EXTENSION_ODD = 1; uint8 constant PREFIX_LEAF_EVEN = 2; uint8 constant PREFIX_LEAF_ODD = 3; // Just a utility constant. RLP represents `NULL` as 0x80. bytes1 constant RLP_NULL = bytes1(0x80); bytes constant RLP_NULL_BYTES = hex'80'; bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES); /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { ( bool exists, bytes memory value ) = get(_key, _proof, _root); return ( exists && Lib_BytesUtils.equal(_value, value) ); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { // Special case when inserting the very first node. if (_root == KECCAK256_RLP_NULL_BYTES) { return getSingleNodeRootHash(_key, _value); } TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root); TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value); return _getUpdatedTrieRoot(newPath, _key); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root); bool exists = keyRemainder.length == 0; require( exists || isFinalNode, "Provided proof is invalid." ); bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes(""); return ( exists, value ); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { return keccak256(_makeLeafNode( Lib_BytesUtils.toNibbles(_key), _value ).encoded); } /********************* * Private Functions * *********************/ /** * @notice Walks through a proof using a provided key. * @param _proof Inclusion proof to walk through. * @param _key Key to use for the walk. * @param _root Known root of the trie. * @return _pathLength Length of the final path * @return _keyRemainder Portion of the key remaining after the walk. * @return _isFinalNode Whether or not we've hit a dead end. */ function _walkNodePath( TrieNode[] memory _proof, bytes memory _key, bytes32 _root ) private pure returns ( uint256 _pathLength, bytes memory _keyRemainder, bool _isFinalNode ) { uint256 pathLength = 0; bytes memory key = Lib_BytesUtils.toNibbles(_key); bytes32 currentNodeID = _root; uint256 currentKeyIndex = 0; uint256 currentKeyIncrement = 0; TrieNode memory currentNode; // Proof is top-down, so we start at the first element (root). for (uint256 i = 0; i < _proof.length; i++) { currentNode = _proof[i]; currentKeyIndex += currentKeyIncrement; // Keep track of the proof elements we actually need. // It's expensive to resize arrays, so this simply reduces gas costs. pathLength += 1; if (currentKeyIndex == 0) { // First proof element is always the root node. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid root hash" ); } else if (currentNode.encoded.length >= 32) { // Nodes 32 bytes or larger are hashed inside branch nodes. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid large internal hash" ); } else { // Nodes smaller than 31 bytes aren't hashed. require( Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID, "Invalid internal node hash" ); } if (currentNode.decoded.length == BRANCH_NODE_LENGTH) { if (currentKeyIndex == key.length) { // We've hit the end of the key // meaning the value should be within this branch node. break; } else { // We're not at the end of the key yet. // Figure out what the next node ID should be and continue. uint8 branchKey = uint8(key[currentKeyIndex]); Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey]; currentNodeID = _getNodeID(nextNode); currentKeyIncrement = 1; continue; } } else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(currentNode); uint8 prefix = uint8(path[0]); uint8 offset = 2 - prefix % 2; bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset); bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex); uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { if ( pathRemainder.length == sharedNibbleLength && keyRemainder.length == sharedNibbleLength ) { // The key within this leaf matches our key exactly. // Increment the key index to reflect that we have no remainder. currentKeyIndex += sharedNibbleLength; } // We've hit a leaf node, so our next node should be NULL. currentNodeID = bytes32(RLP_NULL); break; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { if (sharedNibbleLength != pathRemainder.length) { // Our extension node is not identical to the remainder. // We've hit the end of this path // updates will need to modify this extension. currentNodeID = bytes32(RLP_NULL); break; } else { // Our extension shares some nibbles. // Carry on to the next node. currentNodeID = _getNodeID(currentNode.decoded[1]); currentKeyIncrement = sharedNibbleLength; continue; } } else { revert("Received a node with an unknown prefix"); } } else { revert("Received an unparseable node."); } } // If our node ID is NULL, then we're at a dead end. bool isFinalNode = currentNodeID == bytes32(RLP_NULL); return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode); } /** * @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path. * @param _path Path to the node nearest the k/v pair. * @param _pathLength Length of the path. Necessary because the provided path may include * additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory * arrays without costly duplication. * @param _key Full original key. * @param _keyRemainder Portion of the initial key that must be inserted into the trie. * @param _value Value to insert at the given key. * @return _newPath A new path with the inserted k/v pair and extra supporting nodes. */ function _getNewPath( TrieNode[] memory _path, uint256 _pathLength, bytes memory _key, bytes memory _keyRemainder, bytes memory _value ) private pure returns ( TrieNode[] memory _newPath ) { bytes memory keyRemainder = _keyRemainder; // Most of our logic depends on the status of the last node in the path. TrieNode memory lastNode = _path[_pathLength - 1]; NodeType lastNodeType = _getNodeType(lastNode); // Create an array for newly created nodes. // We need up to three new nodes, depending on the contents of the last node. // Since array resizing is expensive, we'll keep track of the size manually. // We're using an explicit `totalNewNodes += 1` after insertions for clarity. TrieNode[] memory newNodes = new TrieNode[](3); uint256 totalNewNodes = 0; // solhint-disable-next-line max-line-length // Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313 bool matchLeaf = false; if (lastNodeType == NodeType.LeafNode) { uint256 l = 0; if (_path.length > 0) { for (uint256 i = 0; i < _path.length - 1; i++) { if (_getNodeType(_path[i]) == NodeType.BranchNode) { l++; } else { l += _getNodeKey(_path[i]).length; } } } if ( _getSharedNibbleLength( _getNodeKey(lastNode), Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l) ) == _getNodeKey(lastNode).length && keyRemainder.length == 0 ) { matchLeaf = true; } } if (matchLeaf) { // We've found a leaf node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value); totalNewNodes += 1; } else if (lastNodeType == NodeType.BranchNode) { if (keyRemainder.length == 0) { // We've found a branch node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _editBranchValue(lastNode, _value); totalNewNodes += 1; } else { // We've found a branch node, but it doesn't contain our key. // Reinsert the old branch for now. newNodes[totalNewNodes] = lastNode; totalNewNodes += 1; // Create a new leaf node, slicing our remainder since the first byte points // to our branch node. newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value); totalNewNodes += 1; } } else { // Our last node is either an extension node or a leaf node with a different key. bytes memory lastNodeKey = _getNodeKey(lastNode); uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder); if (sharedNibbleLength != 0) { // We've got some shared nibbles between the last node and our key remainder. // We'll need to insert an extension node that covers these shared nibbles. bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength); newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value)); totalNewNodes += 1; // Cut down the keys since we've just covered these shared nibbles. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength); keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength); } // Create an empty branch to fill in. TrieNode memory newBranch = _makeEmptyBranchNode(); if (lastNodeKey.length == 0) { // Key remainder was larger than the key for our last node. // The value within our last node is therefore going to be shifted into // a branch value slot. newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode)); } else { // Last node key was larger than the key remainder. // We're going to modify some index of our branch. uint8 branchKey = uint8(lastNodeKey[0]); // Move on to the next nibble. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1); if (lastNodeType == NodeType.LeafNode) { // We're dealing with a leaf node. // We'll modify the key and insert the old leaf node into the branch index. TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex( newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else if (lastNodeKey.length != 0) { // We're dealing with a shrinking extension node. // We need to modify the node to decrease the size of the key. TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex( newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else { // We're dealing with an unnecessary extension node. // We're going to delete the node entirely. // Simply insert its current value into the branch index. newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode)); } } if (keyRemainder.length == 0) { // We've got nothing left in the key remainder. // Simply insert the value into the branch value slot. newBranch = _editBranchValue(newBranch, _value); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; } else { // We've got some key remainder to work with. // We'll be inserting a leaf node into the trie. // First, move on to the next nibble. keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; // Push a new leaf node for our k/v pair. newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value); totalNewNodes += 1; } } // Finally, join the old path with our newly created nodes. // Since we're overwriting the last node in the path, we use `_pathLength - 1`. return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes); } /** * @notice Computes the trie root from a given path. * @param _nodes Path to some k/v pair. * @param _key Key for the k/v pair. * @return _updatedRoot Root hash for the updated trie. */ function _getUpdatedTrieRoot( TrieNode[] memory _nodes, bytes memory _key ) private pure returns ( bytes32 _updatedRoot ) { bytes memory key = Lib_BytesUtils.toNibbles(_key); // Some variables to keep track of during iteration. TrieNode memory currentNode; NodeType currentNodeType; bytes memory previousNodeHash; // Run through the path backwards to rebuild our root hash. for (uint256 i = _nodes.length; i > 0; i--) { // Pick out the current node. currentNode = _nodes[i - 1]; currentNodeType = _getNodeType(currentNode); if (currentNodeType == NodeType.LeafNode) { // Leaf nodes are already correctly encoded. // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); } else if (currentNodeType == NodeType.ExtensionNode) { // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. currentNode = _editExtensionNodeValue(currentNode, previousNodeHash); } } else if (currentNodeType == NodeType.BranchNode) { // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. uint8 branchKey = uint8(key[key.length - 1]); key = Lib_BytesUtils.slice(key, 0, key.length - 1); currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash); } } // Compute the node hash for the next iteration. previousNodeHash = _getNodeHash(currentNode.encoded); } // Current node should be the root at this point. // Simply return the hash of its encoding. return keccak256(currentNode.encoded); } /** * @notice Parses an RLP-encoded proof into something more useful. * @param _proof RLP-encoded proof to parse. * @return _parsed Proof parsed into easily accessible structs. */ function _parseProof( bytes memory _proof ) private pure returns ( TrieNode[] memory _parsed ) { Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof); TrieNode[] memory proof = new TrieNode[](nodes.length); for (uint256 i = 0; i < nodes.length; i++) { bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]); proof[i] = TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } return proof; } /** * @notice Picks out the ID for a node. Node ID is referred to as the * "hash" within the specification, but nodes < 32 bytes are not actually * hashed. * @param _node Node to pull an ID for. * @return _nodeID ID for the node, depending on the size of its contents. */ function _getNodeID( Lib_RLPReader.RLPItem memory _node ) private pure returns ( bytes32 _nodeID ) { bytes memory nodeID; if (_node.length < 32) { // Nodes smaller than 32 bytes are RLP encoded. nodeID = Lib_RLPReader.readRawBytes(_node); } else { // Nodes 32 bytes or larger are hashed. nodeID = Lib_RLPReader.readBytes(_node); } return Lib_BytesUtils.toBytes32(nodeID); } /** * @notice Gets the path for a leaf or extension node. * @param _node Node to get a path for. * @return _path Node path, converted to an array of nibbles. */ function _getNodePath( TrieNode memory _node ) private pure returns ( bytes memory _path ) { return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0])); } /** * @notice Gets the key for a leaf or extension node. Keys are essentially * just paths without any prefix. * @param _node Node to get a key for. * @return _key Node key, converted to an array of nibbles. */ function _getNodeKey( TrieNode memory _node ) private pure returns ( bytes memory _key ) { return _removeHexPrefix(_getNodePath(_node)); } /** * @notice Gets the path for a node. * @param _node Node to get a value for. * @return _value Node value, as hex bytes. */ function _getNodeValue( TrieNode memory _node ) private pure returns ( bytes memory _value ) { return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]); } /** * @notice Computes the node hash for an encoded node. Nodes < 32 bytes * are not hashed, all others are keccak256 hashed. * @param _encoded Encoded node to hash. * @return _hash Hash of the encoded node. Simply the input if < 32 bytes. */ function _getNodeHash( bytes memory _encoded ) private pure returns ( bytes memory _hash ) { if (_encoded.length < 32) { return _encoded; } else { return abi.encodePacked(keccak256(_encoded)); } } /** * @notice Determines the type for a given node. * @param _node Node to determine a type for. * @return _type Type of the node; BranchNode/ExtensionNode/LeafNode. */ function _getNodeType( TrieNode memory _node ) private pure returns ( NodeType _type ) { if (_node.decoded.length == BRANCH_NODE_LENGTH) { return NodeType.BranchNode; } else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(_node); uint8 prefix = uint8(path[0]); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { return NodeType.LeafNode; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { return NodeType.ExtensionNode; } } revert("Invalid node type"); } /** * @notice Utility; determines the number of nibbles shared between two * nibble arrays. * @param _a First nibble array. * @param _b Second nibble array. * @return _shared Number of shared nibbles. */ function _getSharedNibbleLength( bytes memory _a, bytes memory _b ) private pure returns ( uint256 _shared ) { uint256 i = 0; while (_a.length > i && _b.length > i && _a[i] == _b[i]) { i++; } return i; } /** * @notice Utility; converts an RLP-encoded node into our nice struct. * @param _raw RLP-encoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( bytes[] memory _raw ) private pure returns ( TrieNode memory _node ) { bytes memory encoded = Lib_RLPWriter.writeList(_raw); return TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } /** * @notice Utility; converts an RLP-decoded node into our nice struct. * @param _items RLP-decoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( Lib_RLPReader.RLPItem[] memory _items ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](_items.length); for (uint256 i = 0; i < _items.length; i++) { raw[i] = Lib_RLPReader.readRawBytes(_items[i]); } return _makeNode(raw); } /** * @notice Creates a new extension node. * @param _key Key for the extension node, unprefixed. * @param _value Value for the extension node. * @return _node New extension node with the given k/v pair. */ function _makeExtensionNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * Creates a new extension node with the same key but a different value. * @param _node Extension node to copy and modify. * @param _value New value for the extension node. * @return New node with the same key and different value. */ function _editExtensionNodeValue( TrieNode memory _node, bytes memory _value ) private pure returns ( TrieNode memory ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_getNodeKey(_node), false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); if (_value.length < 32) { raw[1] = _value; } else { raw[1] = Lib_RLPWriter.writeBytes(_value); } return _makeNode(raw); } /** * @notice Creates a new leaf node. * @dev This function is essentially identical to `_makeExtensionNode`. * Although we could route both to a single method with a flag, it's * more gas efficient to keep them separate and duplicate the logic. * @param _key Key for the leaf node, unprefixed. * @param _value Value for the leaf node. * @return _node New leaf node with the given k/v pair. */ function _makeLeafNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, true); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * @notice Creates an empty branch node. * @return _node Empty branch node as a TrieNode struct. */ function _makeEmptyBranchNode() private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH); for (uint256 i = 0; i < raw.length; i++) { raw[i] = RLP_NULL_BYTES; } return _makeNode(raw); } /** * @notice Modifies the value slot for a given branch. * @param _branch Branch node to modify. * @param _value Value to insert into the branch. * @return _updatedNode Modified branch node. */ function _editBranchValue( TrieNode memory _branch, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = Lib_RLPWriter.writeBytes(_value); _branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Modifies a slot at an index for a given branch. * @param _branch Branch node to modify. * @param _index Slot index to modify. * @param _value Value to insert into the slot. * @return _updatedNode Modified branch node. */ function _editBranchIndex( TrieNode memory _branch, uint8 _index, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value); _branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Utility; adds a prefix to a key. * @param _key Key to prefix. * @param _isLeaf Whether or not the key belongs to a leaf. * @return _prefixedKey Prefixed key. */ function _addHexPrefix( bytes memory _key, bool _isLeaf ) private pure returns ( bytes memory _prefixedKey ) { uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00); uint8 offset = uint8(_key.length % 2); bytes memory prefixed = new bytes(2 - offset); prefixed[0] = bytes1(prefix + offset); return abi.encodePacked(prefixed, _key); } /** * @notice Utility; removes a prefix from a path. * @param _path Path to remove the prefix from. * @return _unprefixedKey Unprefixed key. */ function _removeHexPrefix( bytes memory _path ) private pure returns ( bytes memory _unprefixedKey ) { if (uint8(_path[0]) % 2 == 0) { return Lib_BytesUtils.slice(_path, 2); } else { return Lib_BytesUtils.slice(_path, 1); } } /** * @notice Utility; combines two node arrays. Array lengths are required * because the actual lengths may be longer than the filled lengths. * Array resizing is extremely costly and should be avoided. * @param _a First array to join. * @param _aLength Length of the first array. * @param _b Second array to join. * @param _bLength Length of the second array. * @return _joined Combined node array. */ function _joinNodeArrays( TrieNode[] memory _a, uint256 _aLength, TrieNode[] memory _b, uint256 _bLength ) private pure returns ( TrieNode[] memory _joined ) { TrieNode[] memory ret = new TrieNode[](_aLength + _bLength); // Copy elements from the first array. for (uint256 i = 0; i < _aLength; i++) { ret[i] = _a[i]; } // Copy elements from the second array. for (uint256 i = 0; i < _bLength; i++) { ret[i + _aLength] = _b[i]; } return ret; } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol"; import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; /* Contract Imports */ import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol"; /** * @title OVM_StateTransitionerFactory * @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State * Transitioner during the initialization of a fraud proof. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver { /*************** * Constructor * ***************/ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /******************** * Public Functions * ********************/ /** * Creates a new OVM_StateTransitioner * @param _libAddressManager Address of the Address Manager. * @param _stateTransitionIndex Index of the state transition being verified. * @param _preStateRoot State root before the transition was executed. * @param _transactionHash Hash of the executed transaction. * @return New OVM_StateTransitioner instance. */ function create( address _libAddressManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) override public returns ( iOVM_StateTransitioner ) { require( msg.sender == resolve("OVM_FraudVerifier"), "Create can only be done by the OVM_FraudVerifier." ); return new OVM_StateTransitioner( _libAddressManager, _stateTransitionIndex, _preStateRoot, _transactionHash ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol"; /** * @title iOVM_StateTransitionerFactory */ interface iOVM_StateTransitionerFactory { /*************************************** * Public Functions: Contract Creation * ***************************************/ function create( address _proxyManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) external returns ( iOVM_StateTransitioner _ovmStateTransitioner ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol"; /** * @title iOVM_FraudVerifier */ interface iOVM_FraudVerifier { /********** * Events * **********/ event FraudProofInitialized( bytes32 _preStateRoot, uint256 _preStateRootIndex, bytes32 _transactionHash, address _who ); event FraudProofFinalized( bytes32 _preStateRoot, uint256 _preStateRootIndex, bytes32 _transactionHash, address _who ); /*************************************** * Public Functions: Transition Status * ***************************************/ function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner); /**************************************** * Public Functions: Fraud Verification * ****************************************/ function initializeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof, Lib_OVMCodec.Transaction calldata _transaction, Lib_OVMCodec.TransactionChainElement calldata _txChainElement, Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _transactionProof ) external; function finalizeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof, bytes32 _txHash, bytes32 _postStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol"; import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; /* Contract Imports */ import { Abs_FraudContributor } from "./Abs_FraudContributor.sol"; /** * @title OVM_FraudVerifier * @dev The Fraud Verifier contract coordinates the entire fraud proof verification process. * If the fraud proof was successful it prunes any state batches from State Commitment Chain * which were published after the fraudulent state root. * * Compiler used: solc * Runtime target: EVM */ contract OVM_FraudVerifier is Lib_AddressResolver, Abs_FraudContributor, iOVM_FraudVerifier { /******************************************* * Contract Variables: Internal Accounting * *******************************************/ mapping (bytes32 => iOVM_StateTransitioner) internal transitioners; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /*************************************** * Public Functions: Transition Status * ***************************************/ /** * Retrieves the state transitioner for a given root. * @param _preStateRoot State root to query a transitioner for. * @return _transitioner Corresponding state transitioner contract. */ function getStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) override public view returns ( iOVM_StateTransitioner _transitioner ) { return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))]; } /**************************************** * Public Functions: Fraud Verification * ****************************************/ /** * Begins the fraud verification process. * @param _preStateRoot State root before the fraudulent transaction. * @param _preStateRootBatchHeader Batch header for the provided pre-state root. * @param _preStateRootProof Inclusion proof for the provided pre-state root. * @param _transaction OVM transaction claimed to be fraudulent. * @param _txChainElement OVM transaction chain element. * @param _transactionBatchHeader Batch header for the provided transaction. * @param _transactionProof Inclusion proof for the provided transaction. */ function initializeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof, Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _transactionBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _transactionProof ) override public contributesToFraudProof(_preStateRoot, Lib_OVMCodec.hashTransaction(_transaction)) { bytes32 _txHash = Lib_OVMCodec.hashTransaction(_transaction); if (_hasStateTransitioner(_preStateRoot, _txHash)) { return; } iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); iOVM_CanonicalTransactionChain ovmCanonicalTransactionChain = iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")); require( ovmStateCommitmentChain.verifyStateCommitment( _preStateRoot, _preStateRootBatchHeader, _preStateRootProof ), "Invalid pre-state root inclusion proof." ); require( ovmCanonicalTransactionChain.verifyTransaction( _transaction, _txChainElement, _transactionBatchHeader, _transactionProof ), "Invalid transaction inclusion proof." ); require ( // solhint-disable-next-line max-line-length _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1 == _transactionBatchHeader.prevTotalElements + _transactionProof.index, "Pre-state root global index must equal to the transaction root global index." ); _deployTransitioner(_preStateRoot, _txHash, _preStateRootProof.index); emit FraudProofInitialized( _preStateRoot, _preStateRootProof.index, _txHash, msg.sender ); } /** * Finalizes the fraud verification process. * @param _preStateRoot State root before the fraudulent transaction. * @param _preStateRootBatchHeader Batch header for the provided pre-state root. * @param _preStateRootProof Inclusion proof for the provided pre-state root. * @param _txHash The transaction for the state root * @param _postStateRoot State root after the fraudulent transaction. * @param _postStateRootBatchHeader Batch header for the provided post-state root. * @param _postStateRootProof Inclusion proof for the provided post-state root. */ function finalizeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof, bytes32 _txHash, bytes32 _postStateRoot, Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _postStateRootProof ) override public contributesToFraudProof(_preStateRoot, _txHash) { iOVM_StateTransitioner transitioner = getStateTransitioner(_preStateRoot, _txHash); iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); require( transitioner.isComplete() == true, "State transition process must be completed prior to finalization." ); require ( // solhint-disable-next-line max-line-length _postStateRootBatchHeader.prevTotalElements + _postStateRootProof.index == _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1, "Post-state root global index must equal to the pre state root global index plus one." ); require( ovmStateCommitmentChain.verifyStateCommitment( _preStateRoot, _preStateRootBatchHeader, _preStateRootProof ), "Invalid pre-state root inclusion proof." ); require( ovmStateCommitmentChain.verifyStateCommitment( _postStateRoot, _postStateRootBatchHeader, _postStateRootProof ), "Invalid post-state root inclusion proof." ); // If the post state root did not match, then there was fraud and we should delete the batch require( _postStateRoot != transitioner.getPostStateRoot(), "State transition has not been proven fraudulent." ); _cancelStateTransition(_postStateRootBatchHeader, _preStateRoot); // TEMPORARY: Remove the transitioner; for minnet. transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitioner(0x0000000000000000000000000000000000000000); emit FraudProofFinalized( _preStateRoot, _preStateRootProof.index, _txHash, msg.sender ); } /************************************ * Internal Functions: Verification * ************************************/ /** * Checks whether a transitioner already exists for a given pre-state root. * @param _preStateRoot Pre-state root to check. * @return _exists Whether or not we already have a transitioner for the root. */ function _hasStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) internal view returns ( bool _exists ) { return address(getStateTransitioner(_preStateRoot, _txHash)) != address(0); } /** * Deploys a new state transitioner. * @param _preStateRoot Pre-state root to initialize the transitioner with. * @param _txHash Hash of the transaction this transitioner will execute. * @param _stateTransitionIndex Index of the transaction in the chain. */ function _deployTransitioner( bytes32 _preStateRoot, bytes32 _txHash, uint256 _stateTransitionIndex ) internal { transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitionerFactory( resolve("OVM_StateTransitionerFactory") ).create( address(libAddressManager), _stateTransitionIndex, _preStateRoot, _txHash ); } /** * Removes a state transition from the state commitment chain. * @param _postStateRootBatchHeader Header for the post-state root. * @param _preStateRoot Pre-state root hash. */ function _cancelStateTransition( Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader, bytes32 _preStateRoot ) internal { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); iOVM_BondManager ovmBondManager = iOVM_BondManager(resolve("OVM_BondManager")); // Delete the state batch. ovmStateCommitmentChain.deleteStateBatch( _postStateRootBatchHeader ); // Get the timestamp and publisher for that block. (uint256 timestamp, address publisher) = abi.decode(_postStateRootBatchHeader.extraData, (uint256, address)); // Slash the bonds at the bond manager. ovmBondManager.finalize( _preStateRoot, publisher, timestamp ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateCommitmentChain */ interface iOVM_StateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted( uint256 indexed _batchIndex, bytes32 _batchRoot ); /******************** * Public Functions * ********************/ /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns ( uint256 _totalBatches ); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns ( uint256 _lastSequencerTimestamp ); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch( bytes32[] calldata _batch, uint256 _shouldStartAtElement ) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns ( bool _verified ); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns ( bool _inside ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol"; /** * @title iOVM_CanonicalTransactionChain */ interface iOVM_CanonicalTransactionChain { /********** * Events * **********/ event TransactionEnqueued( address _l1TxOrigin, address _target, uint256 _gasLimit, bytes _data, uint256 _queueIndex, uint256 _timestamp ); event QueueBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event SequencerBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event TransactionBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); /*********** * Structs * ***********/ struct BatchContext { uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 timestamp; uint256 blockNumber; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() external view returns ( iOVM_ChainStorageContainer ); /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() external view returns ( iOVM_ChainStorageContainer ); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns ( uint256 _totalBatches ); /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() external view returns ( uint40 ); /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElement( uint256 _index ) external view returns ( Lib_OVMCodec.QueueElement memory _element ); /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() external view returns ( uint40 ); /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() external view returns ( uint40 ); /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() external view returns ( uint40 ); /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() external view returns ( uint40 ); /** * Adds a transaction to the queue. * @param _target Target contract to send the transaction to. * @param _gasLimit Gas limit for the given transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) external; /** * Appends a given number of queued transactions as a single batch. * @param _numQueuedTransactions Number of transactions to append. */ function appendQueueBatch( uint256 _numQueuedTransactions ) external; /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatch( // uint40 _shouldStartAtElement, // uint24 _totalElementsToAppend, // BatchContext[] _contexts, // bytes[] _transactionDataFields ) external; /** * Verifies whether a transaction is included in the chain. * @param _transaction Transaction to verify. * @param _txChainElement Transaction chain element corresponding to the transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof Inclusion proof for the provided transaction chain element. * @return True if the transaction exists in the CTC, false if not. */ function verifyTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) external view returns ( bool ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_ChainStorageContainer */ interface iOVM_ChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata( bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns ( uint256 ); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push( bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push( bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get( uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive( uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_BondManager, Errors, ERC20 } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; /** * @title OVM_BondManager * @dev The Bond Manager contract handles deposits in the form of an ERC20 token from bonded * Proposers. It also handles the accounting of gas costs spent by a Verifier during the course of a * fraud proof. In the event of a successful fraud proof, the fraudulent Proposer's bond is slashed, * and the Verifier's gas costs are refunded. * * Compiler used: solc * Runtime target: EVM */ contract OVM_BondManager is iOVM_BondManager, Lib_AddressResolver { /**************************** * Constants and Parameters * ****************************/ /// The period to find the earliest fraud proof for a publisher uint256 public constant multiFraudProofPeriod = 7 days; /// The dispute period uint256 public constant disputePeriodSeconds = 7 days; /// The minimum collateral a sequencer must post uint256 public constant requiredCollateral = 1 ether; /******************************************* * Contract Variables: Contract References * *******************************************/ /// The bond token ERC20 immutable public token; /******************************************** * Contract Variables: Internal Accounting * *******************************************/ /// The bonds posted by each proposer mapping(address => Bond) public bonds; /// For each pre-state root, there's an array of witnessProviders that must be rewarded /// for posting witnesses mapping(bytes32 => Rewards) public witnessProviders; /*************** * Constructor * ***************/ /// Initializes with a ERC20 token to be used for the fidelity bonds /// and with the Address Manager constructor( ERC20 _token, address _libAddressManager ) Lib_AddressResolver(_libAddressManager) { token = _token; } /******************** * Public Functions * ********************/ /// Adds `who` to the list of witnessProviders for the provided `preStateRoot`. function recordGasSpent(bytes32 _preStateRoot, bytes32 _txHash, address who, uint256 gasSpent) override public { // The sender must be the transitioner that corresponds to the claimed pre-state root address transitioner = address(iOVM_FraudVerifier(resolve("OVM_FraudVerifier")) .getStateTransitioner(_preStateRoot, _txHash)); require(transitioner == msg.sender, Errors.ONLY_TRANSITIONER); witnessProviders[_preStateRoot].total += gasSpent; witnessProviders[_preStateRoot].gasSpent[who] += gasSpent; } /// Slashes + distributes rewards or frees up the sequencer's bond, only called by /// `FraudVerifier.finalizeFraudVerification` function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) override public { require(msg.sender == resolve("OVM_FraudVerifier"), Errors.ONLY_FRAUD_VERIFIER); require(witnessProviders[_preStateRoot].canClaim == false, Errors.ALREADY_FINALIZED); // allow users to claim from that state root's // pool of collateral (effectively slashing the sequencer) witnessProviders[_preStateRoot].canClaim = true; Bond storage bond = bonds[publisher]; if (bond.firstDisputeAt == 0) { bond.firstDisputeAt = block.timestamp; bond.earliestDisputedStateRoot = _preStateRoot; bond.earliestTimestamp = timestamp; } else if ( // only update the disputed state root for the publisher if it's within // the dispute period _and_ if it's before the previous one block.timestamp < bond.firstDisputeAt + multiFraudProofPeriod && timestamp < bond.earliestTimestamp ) { bond.earliestDisputedStateRoot = _preStateRoot; bond.earliestTimestamp = timestamp; } // if the fraud proof's dispute period does not intersect with the // withdrawal's timestamp, then the user should not be slashed // e.g if a user at day 10 submits a withdrawal, and a fraud proof // from day 1 gets published, the user won't be slashed since day 8 (1d + 7d) // is before the user started their withdrawal. on the contrary, if the user // had started their withdrawal at, say, day 6, they would be slashed if ( bond.withdrawalTimestamp != 0 && uint256(bond.withdrawalTimestamp) > timestamp + disputePeriodSeconds && bond.state == State.WITHDRAWING ) { return; } // slash! bond.state = State.NOT_COLLATERALIZED; } /// Sequencers call this function to post collateral which will be used for /// the `appendBatch` call function deposit() override public { require( token.transferFrom(msg.sender, address(this), requiredCollateral), Errors.ERC20_ERR ); // This cannot overflow bonds[msg.sender].state = State.COLLATERALIZED; } /// Starts the withdrawal for a publisher function startWithdrawal() override public { Bond storage bond = bonds[msg.sender]; require(bond.withdrawalTimestamp == 0, Errors.WITHDRAWAL_PENDING); require(bond.state == State.COLLATERALIZED, Errors.WRONG_STATE); bond.state = State.WITHDRAWING; bond.withdrawalTimestamp = uint32(block.timestamp); } /// Finalizes a pending withdrawal from a publisher function finalizeWithdrawal() override public { Bond storage bond = bonds[msg.sender]; require( block.timestamp >= uint256(bond.withdrawalTimestamp) + disputePeriodSeconds, Errors.TOO_EARLY ); require(bond.state == State.WITHDRAWING, Errors.SLASHED); // refunds! bond.state = State.NOT_COLLATERALIZED; bond.withdrawalTimestamp = 0; require( token.transfer(msg.sender, requiredCollateral), Errors.ERC20_ERR ); } /// Claims the user's reward for the witnesses they provided for the earliest /// disputed state root of the designated publisher function claim(address who) override public { Bond storage bond = bonds[who]; require( block.timestamp >= bond.firstDisputeAt + multiFraudProofPeriod, Errors.WAIT_FOR_DISPUTES ); // reward the earliest state root for this publisher bytes32 _preStateRoot = bond.earliestDisputedStateRoot; Rewards storage rewards = witnessProviders[_preStateRoot]; // only allow claiming if fraud was proven in `finalize` require(rewards.canClaim, Errors.CANNOT_CLAIM); // proportional allocation - only reward 50% (rest gets locked in the // contract forever uint256 amount = (requiredCollateral * rewards.gasSpent[msg.sender]) / (2 * rewards.total); // reset the user's spent gas so they cannot double claim rewards.gasSpent[msg.sender] = 0; // transfer require(token.transfer(msg.sender, amount), Errors.ERC20_ERR); } /// Checks if the user is collateralized function isCollateralized(address who) override public view returns (bool) { return bonds[who].state == State.COLLATERALIZED; } /// Gets how many witnesses the user has provided for the state root function getGasSpent(bytes32 preStateRoot, address who) override public view returns (uint256) { return witnessProviders[preStateRoot].gasSpent[who]; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; import { OVM_BondManager } from "./../optimistic-ethereum/OVM/verification/OVM_BondManager.sol"; contract Mock_FraudVerifier { OVM_BondManager bondManager; mapping (bytes32 => address) transitioners; function setBondManager(OVM_BondManager _bondManager) public { bondManager = _bondManager; } function setStateTransitioner(bytes32 preStateRoot, bytes32 txHash, address addr) public { transitioners[keccak256(abi.encodePacked(preStateRoot, txHash))] = addr; } function getStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) public view returns ( address ) { return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))]; } function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) public { bondManager.finalize(_preStateRoot, publisher, timestamp); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol"; import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /* External Imports */ import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title OVM_StateCommitmentChain * @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which * Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). * Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique * state root calculated off-chain by applying the canonical transactions one by one. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateCommitmentChain is iOVM_StateCommitmentChain, Lib_AddressResolver { /************* * Constants * *************/ uint256 public FRAUD_PROOF_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow ) Lib_AddressResolver(_libAddressManager) { FRAUD_PROOF_WINDOW = _fraudProofWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-SCC-batches") ); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getTotalElements() override public view returns ( uint256 _totalElements ) { (uint40 totalElements, ) = _getBatchExtraData(); return uint256(totalElements); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getTotalBatches() override public view returns ( uint256 _totalBatches ) { return batches().length(); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getLastSequencerTimestamp() override public view returns ( uint256 _lastSequencerTimestamp ) { (, uint40 lastSequencerTimestamp) = _getBatchExtraData(); return uint256(lastSequencerTimestamp); } /** * @inheritdoc iOVM_StateCommitmentChain */ function appendStateBatch( bytes32[] memory _batch, uint256 _shouldStartAtElement ) override public { // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the // publication of batches by some other user. require( _shouldStartAtElement == getTotalElements(), "Actual batch start index does not match expected start index." ); // Proposers must have previously staked at the BondManager require( iOVM_BondManager(resolve("OVM_BondManager")).isCollateralized(msg.sender), "Proposer does not have enough collateral posted" ); require( _batch.length > 0, "Cannot submit an empty state batch." ); require( getTotalElements() + _batch.length <= iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")) .getTotalElements(), "Number of state roots cannot exceed the number of canonical transactions." ); // Pass the block's timestamp and the publisher of the data // to be used in the fraud proofs _appendBatch( _batch, abi.encode(block.timestamp, msg.sender) ); } /** * @inheritdoc iOVM_StateCommitmentChain */ function deleteStateBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public { require( msg.sender == resolve("OVM_FraudVerifier"), "State batches can only be deleted by the OVM_FraudVerifier." ); require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); require( insideFraudProofWindow(_batchHeader), "State batches can only be deleted within the fraud proof window." ); _deleteBatch(_batchHeader); } /** * @inheritdoc iOVM_StateCommitmentChain */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) override public view returns ( bool ) { require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } /** * @inheritdoc iOVM_StateCommitmentChain */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public view returns ( bool _inside ) { (uint256 timestamp,) = abi.decode( _batchHeader.extraData, (uint256, address) ); require( timestamp != 0, "Batch header timestamp cannot be zero" ); return SafeMath.add(timestamp, FRAUD_PROOF_WINDOW) > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraData() internal view returns ( uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadata(); // solhint-disable max-line-length uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } // solhint-enable max-line-length return ( totalElements, lastSequencerTimestamp ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraData( uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * Appends a batch to the chain. * @param _batch Elements within the batch. * @param _extraData Any extra data to append to the batch. */ function _appendBatch( bytes32[] memory _batch, bytes memory _extraData ) internal { address sequencer = resolve("OVM_Proposer"); (uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraData(); if (msg.sender == sequencer) { lastSequencerTimestamp = uint40(block.timestamp); } else { // We keep track of the last batch submitted by the sequencer so there's a window in // which only the sequencer can publish state roots. A window like this just reduces // the chance of "system breaking" state roots being published while we're still in // testing mode. This window should be removed or significantly reduced in the future. require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, "Cannot publish state roots within the sequencer publication window." ); } // For efficiency reasons getMerkleRoot modifies the `_batch` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({ batchIndex: getTotalBatches(), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().push( Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraData( uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } /** * Removes a batch and all subsequent batches from the chain. * @param _batchHeader Header of the batch to remove. */ function _deleteBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal { require( _batchHeader.batchIndex < batches().length(), "Invalid batch index." ); require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); batches().deleteElementsAfterInclusive( _batchHeader.batchIndex, _makeBatchExtraData( uint40(_batchHeader.prevTotalElements), 0 ) ); emit StateBatchDeleted( _batchHeader.batchIndex, _batchHeader.batchRoot ); } /** * Checks that a batch header matches the stored hash for the given index. * @param _batchHeader Batch header to validate. * @return Whether or not the header matches the stored one. */ function _isValidBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal view returns ( bool ) { return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_MerkleTree * @author River Keefer */ library Lib_MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, then * this may allow empty leaves past _elements.length to pass a verification check down the line. * Note that the _elements argument is modified, therefore it must not be used again afterwards * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot( bytes32[] memory _elements ) internal pure returns ( bytes32 ) { require( _elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash." ); if (_elements.length == 1) { return _elements[0]; } uint256[16] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i) ]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling ) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 * (bottom of the tree). * @param _totalLeaves The total number of leaves originally passed into. * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns ( bool ) { require( _totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero." ); require( _index < _totalLeaves, "Lib_MerkleTree: Index out of bounds." ); require( _siblings.length == _ceilLog2(_totalLeaves), "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves." ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256( abi.encodePacked( _siblings[i], computedRoot ) ); } else { computedRoot = keccak256( abi.encodePacked( computedRoot, _siblings[i] ) ); } _index >>= 1; } return _root == computedRoot; } /********************* * Private Functions * *********************/ /** * Calculates the integer ceiling of the log base 2 of an input. * @param _in Unsigned input to calculate the log. * @return ceil(log_base_2(_in)) */ function _ceilLog2( uint256 _in ) private pure returns ( uint256 ) { require( _in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0." ); if (_in == 1) { return 0; } // Find the highest set bit (will be floor(log_2)). // Borrowed with <3 from https://github.com/ethereum/solidity-examples uint256 val = _in; uint256 highest = 0; for (uint256 i = 128; i >= 1; i >>= 1) { if (val & (uint(1) << i) - 1 << i != 0) { highest += i; val >>= i; } } // Increment by one if this is not a perfect logarithm. if ((uint(1) << highest) != _in) { highest += 1; } return highest; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Buffer } from "../../libraries/utils/Lib_Buffer.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /** * @title OVM_ChainStorageContainer * @dev The Chain Storage Container provides its owner contract with read, write and delete * functionality. This provides gas efficiency gains by enabling it to overwrite storage slots which * can no longer be used in a fraud proof due to the fraud window having passed, and the associated * chain state or transactions being finalized. * Three distinct Chain Storage Containers will be deployed on Layer 1: * 1. Stores transaction batches for the Canonical Transaction Chain * 2. Stores queued transactions for the Canonical Transaction Chain * 3. Stores chain state batches for the State Commitment Chain * * Compiler used: solc * Runtime target: EVM */ contract OVM_ChainStorageContainer is iOVM_ChainStorageContainer, Lib_AddressResolver { /************* * Libraries * *************/ using Lib_Buffer for Lib_Buffer.Buffer; /************* * Variables * *************/ string public owner; Lib_Buffer.Buffer internal buffer; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. * @param _owner Name of the contract that owns this container (will be resolved later). */ constructor( address _libAddressManager, string memory _owner ) Lib_AddressResolver(_libAddressManager) { owner = _owner; } /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require( msg.sender == resolve(owner), "OVM_ChainStorageContainer: Function can only be called by the owner." ); _; } /******************** * Public Functions * ********************/ /** * @inheritdoc iOVM_ChainStorageContainer */ function setGlobalMetadata( bytes27 _globalMetadata ) override public onlyOwner { return buffer.setExtraData(_globalMetadata); } /** * @inheritdoc iOVM_ChainStorageContainer */ function getGlobalMetadata() override public view returns ( bytes27 ) { return buffer.getExtraData(); } /** * @inheritdoc iOVM_ChainStorageContainer */ function length() override public view returns ( uint256 ) { return uint256(buffer.getLength()); } /** * @inheritdoc iOVM_ChainStorageContainer */ function push( bytes32 _object ) override public onlyOwner { buffer.push(_object); } /** * @inheritdoc iOVM_ChainStorageContainer */ function push( bytes32 _object, bytes27 _globalMetadata ) override public onlyOwner { buffer.push(_object, _globalMetadata); } /** * @inheritdoc iOVM_ChainStorageContainer */ function get( uint256 _index ) override public view returns ( bytes32 ) { return buffer.get(uint40(_index)); } /** * @inheritdoc iOVM_ChainStorageContainer */ function deleteElementsAfterInclusive( uint256 _index ) override public onlyOwner { buffer.deleteElementsAfterInclusive( uint40(_index) ); } /** * @inheritdoc iOVM_ChainStorageContainer */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) override public onlyOwner { buffer.deleteElementsAfterInclusive( uint40(_index), _globalMetadata ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Buffer * @dev This library implements a bytes32 storage array with some additional gas-optimized * functionality. In particular, it encodes its length as a uint40, and tightly packs this with an * overwritable "extra data" field so we can store more information with a single SSTORE. */ library Lib_Buffer { /************* * Libraries * *************/ using Lib_Buffer for Buffer; /*********** * Structs * ***********/ struct Buffer { bytes32 context; mapping (uint256 => bytes32) buf; } struct BufferContext { // Stores the length of the array. Uint40 is way more elements than we'll ever reasonably // need in an array and we get an extra 27 bytes of extra data to play with. uint40 length; // Arbitrary extra data that can be modified whenever the length is updated. Useful for // squeezing out some gas optimizations. bytes27 extraData; } /********************** * Internal Functions * **********************/ /** * Pushes a single element to the buffer. * @param _self Buffer to access. * @param _value Value to push to the buffer. * @param _extraData Global extra data. */ function push( Buffer storage _self, bytes32 _value, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); _self.buf[ctx.length] = _value; // Bump the global index and insert our extra data, then save the context. ctx.length++; ctx.extraData = _extraData; _self.setContext(ctx); } /** * Pushes a single element to the buffer. * @param _self Buffer to access. * @param _value Value to push to the buffer. */ function push( Buffer storage _self, bytes32 _value ) internal { BufferContext memory ctx = _self.getContext(); _self.push( _value, ctx.extraData ); } /** * Retrieves an element from the buffer. * @param _self Buffer to access. * @param _index Element index to retrieve. * @return Value of the element at the given index. */ function get( Buffer storage _self, uint256 _index ) internal view returns ( bytes32 ) { BufferContext memory ctx = _self.getContext(); require( _index < ctx.length, "Index out of bounds." ); return _self.buf[_index]; } /** * Deletes all elements after (and including) a given index. * @param _self Buffer to access. * @param _index Index of the element to delete from (inclusive). * @param _extraData Optional global extra data. */ function deleteElementsAfterInclusive( Buffer storage _self, uint40 _index, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); require( _index < ctx.length, "Index out of bounds." ); // Set our length and extra data, save the context. ctx.length = _index; ctx.extraData = _extraData; _self.setContext(ctx); } /** * Deletes all elements after (and including) a given index. * @param _self Buffer to access. * @param _index Index of the element to delete from (inclusive). */ function deleteElementsAfterInclusive( Buffer storage _self, uint40 _index ) internal { BufferContext memory ctx = _self.getContext(); _self.deleteElementsAfterInclusive( _index, ctx.extraData ); } /** * Retrieves the current global index. * @param _self Buffer to access. * @return Current global index. */ function getLength( Buffer storage _self ) internal view returns ( uint40 ) { BufferContext memory ctx = _self.getContext(); return ctx.length; } /** * Changes current global extra data. * @param _self Buffer to access. * @param _extraData New global extra data. */ function setExtraData( Buffer storage _self, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); ctx.extraData = _extraData; _self.setContext(ctx); } /** * Retrieves the current global extra data. * @param _self Buffer to access. * @return Current global extra data. */ function getExtraData( Buffer storage _self ) internal view returns ( bytes27 ) { BufferContext memory ctx = _self.getContext(); return ctx.extraData; } /** * Sets the current buffer context. * @param _self Buffer to access. * @param _ctx Current buffer context. */ function setContext( Buffer storage _self, BufferContext memory _ctx ) internal { bytes32 context; uint40 length = _ctx.length; bytes27 extraData = _ctx.extraData; assembly { context := length context := or(context, extraData) } if (_self.context != context) { _self.context = context; } } /** * Retrieves the current buffer context. * @param _self Buffer to access. * @return Current buffer context. */ function getContext( Buffer storage _self ) internal view returns ( BufferContext memory ) { bytes32 context = _self.context; uint40 length; bytes27 extraData; assembly { // solhint-disable-next-line max-line-length length := and(context, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) // solhint-disable-next-line max-line-length extraData := and(context, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000) } return BufferContext({ length: length, extraData: extraData }); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_Buffer } from "../../optimistic-ethereum/libraries/utils/Lib_Buffer.sol"; /** * @title TestLib_Buffer */ contract TestLib_Buffer { using Lib_Buffer for Lib_Buffer.Buffer; Lib_Buffer.Buffer internal buf; function push( bytes32 _value, bytes27 _extraData ) public { buf.push( _value, _extraData ); } function get( uint256 _index ) public view returns ( bytes32 ) { return buf.get(_index); } function deleteElementsAfterInclusive( uint40 _index ) public { return buf.deleteElementsAfterInclusive( _index ); } function deleteElementsAfterInclusive( uint40 _index, bytes27 _extraData ) public { return buf.deleteElementsAfterInclusive( _index, _extraData ); } function getLength() public view returns ( uint40 ) { return buf.getLength(); } function setExtraData( bytes27 _extraData ) public { return buf.setExtraData( _extraData ); } function getExtraData() public view returns ( bytes27 ) { return buf.getExtraData(); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /* Contract Imports */ import { OVM_ExecutionManager } from "../execution/OVM_ExecutionManager.sol"; /* External Imports */ import { Math } from "@openzeppelin/contracts/math/Math.sol"; /** * @title OVM_CanonicalTransactionChain * @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions * which must be applied to the rollup state. It defines the ordering of rollup transactions by * writing them to the 'CTC:batches' instance of the Chain Storage Container. * The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the * Sequencer will eventually append it to the rollup state. * If the Sequencer does not include an enqueued transaction within the 'force inclusion period', * then any account may force it to be included by calling appendQueueBatch(). * * Compiler used: solc * Runtime target: EVM */ contract OVM_CanonicalTransactionChain is iOVM_CanonicalTransactionChain, Lib_AddressResolver { /************* * Constants * *************/ // L2 tx gas-related uint256 constant public MIN_ROLLUP_TX_GAS = 100000; uint256 constant public MAX_ROLLUP_TX_SIZE = 50000; uint256 constant public L2_GAS_DISCOUNT_DIVISOR = 32; // Encoding-related (all in bytes) uint256 constant internal BATCH_CONTEXT_SIZE = 16; uint256 constant internal BATCH_CONTEXT_LENGTH_POS = 12; uint256 constant internal BATCH_CONTEXT_START_POS = 15; uint256 constant internal TX_DATA_HEADER_SIZE = 3; uint256 constant internal BYTES_TILL_TX_DATA = 65; /************* * Variables * *************/ uint256 public forceInclusionPeriodSeconds; uint256 public forceInclusionPeriodBlocks; uint256 public maxTransactionGasLimit; /*************** * Constructor * ***************/ constructor( address _libAddressManager, uint256 _forceInclusionPeriodSeconds, uint256 _forceInclusionPeriodBlocks, uint256 _maxTransactionGasLimit ) Lib_AddressResolver(_libAddressManager) { forceInclusionPeriodSeconds = _forceInclusionPeriodSeconds; forceInclusionPeriodBlocks = _forceInclusionPeriodBlocks; maxTransactionGasLimit = _maxTransactionGasLimit; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() override public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-CTC-batches") ); } /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() override public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-CTC-queue") ); } /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() override public view returns ( uint256 _totalElements ) { (uint40 totalElements,,,) = _getBatchExtraData(); return uint256(totalElements); } /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() override public view returns ( uint256 _totalBatches ) { return batches().length(); } /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() override public view returns ( uint40 ) { (,uint40 nextQueueIndex,,) = _getBatchExtraData(); return nextQueueIndex; } /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() override public view returns ( uint40 ) { (,,uint40 lastTimestamp,) = _getBatchExtraData(); return lastTimestamp; } /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() override public view returns ( uint40 ) { (,,,uint40 lastBlockNumber) = _getBatchExtraData(); return lastBlockNumber; } /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElement( uint256 _index ) override public view returns ( Lib_OVMCodec.QueueElement memory _element ) { return _getQueueElement( _index, queue() ); } /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() override public view returns ( uint40 ) { return getQueueLength() - getNextQueueIndex(); } /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() override public view returns ( uint40 ) { return _getQueueLength( queue() ); } /** * Adds a transaction to the queue. * @param _target Target L2 contract to send the transaction to. * @param _gasLimit Gas limit for the enqueued L2 transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) override public { require( _data.length <= MAX_ROLLUP_TX_SIZE, "Transaction data size exceeds maximum for rollup transaction." ); require( _gasLimit <= maxTransactionGasLimit, "Transaction gas limit exceeds maximum for rollup transaction." ); require( _gasLimit >= MIN_ROLLUP_TX_GAS, "Transaction gas limit too low to enqueue." ); // We need to consume some amount of L1 gas in order to rate limit transactions going into // L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the // provided L1 gas. uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR; uint256 startingGas = gasleft(); // Although this check is not necessary (burn below will run out of gas if not true), it // gives the user an explicit reason as to why the enqueue attempt failed. require( startingGas > gasToConsume, "Insufficient gas for L2 rate limiting burn." ); // Here we do some "dumb" work in order to burn gas, although we should probably replace // this with something like minting gas token later on. uint256 i; while(startingGas - gasleft() < gasToConsume) { i++; } bytes32 transactionHash = keccak256( abi.encode( msg.sender, _target, _gasLimit, _data ) ); bytes32 timestampAndBlockNumber; assembly { timestampAndBlockNumber := timestamp() timestampAndBlockNumber := or(timestampAndBlockNumber, shl(40, number())) } iOVM_ChainStorageContainer queueRef = queue(); queueRef.push(transactionHash); queueRef.push(timestampAndBlockNumber); // The underlying queue data structure stores 2 elements // per insertion, so to get the real queue length we need // to divide by 2 and subtract 1. uint256 queueIndex = queueRef.length() / 2 - 1; emit TransactionEnqueued( msg.sender, _target, _gasLimit, _data, queueIndex, block.timestamp ); } /** * Appends a given number of queued transactions as a single batch. * param _numQueuedTransactions Number of transactions to append. */ function appendQueueBatch( uint256 // _numQueuedTransactions ) override public pure { // TEMPORARY: Disable `appendQueueBatch` for minnet revert("appendQueueBatch is currently disabled."); // solhint-disable max-line-length // _numQueuedTransactions = Math.min(_numQueuedTransactions, getNumPendingQueueElements()); // require( // _numQueuedTransactions > 0, // "Must append more than zero transactions." // ); // bytes32[] memory leaves = new bytes32[](_numQueuedTransactions); // uint40 nextQueueIndex = getNextQueueIndex(); // for (uint256 i = 0; i < _numQueuedTransactions; i++) { // if (msg.sender != resolve("OVM_Sequencer")) { // Lib_OVMCodec.QueueElement memory el = getQueueElement(nextQueueIndex); // require( // el.timestamp + forceInclusionPeriodSeconds < block.timestamp, // "Queue transactions cannot be submitted during the sequencer inclusion period." // ); // } // leaves[i] = _getQueueLeafHash(nextQueueIndex); // nextQueueIndex++; // } // Lib_OVMCodec.QueueElement memory lastElement = getQueueElement(nextQueueIndex - 1); // _appendBatch( // Lib_MerkleTree.getMerkleRoot(leaves), // _numQueuedTransactions, // _numQueuedTransactions, // lastElement.timestamp, // lastElement.blockNumber // ); // emit QueueBatchAppended( // nextQueueIndex - _numQueuedTransactions, // _numQueuedTransactions, // getTotalElements() // ); // solhint-enable max-line-length } /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatch() override public { uint40 shouldStartAtElement; uint24 totalElementsToAppend; uint24 numContexts; assembly { shouldStartAtElement := shr(216, calldataload(4)) totalElementsToAppend := shr(232, calldataload(9)) numContexts := shr(232, calldataload(12)) } require( shouldStartAtElement == getTotalElements(), "Actual batch start index does not match expected start index." ); require( msg.sender == resolve("OVM_Sequencer"), "Function can only be called by the Sequencer." ); require( numContexts > 0, "Must provide at least one batch context." ); require( totalElementsToAppend > 0, "Must append at least one element." ); uint40 nextTransactionPtr = uint40( BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts ); require( msg.data.length >= nextTransactionPtr, "Not enough BatchContexts provided." ); // Take a reference to the queue and its length so we don't have to keep resolving it. // Length isn't going to change during the course of execution, so it's fine to simply // resolve this once at the start. Saves gas. iOVM_ChainStorageContainer queueRef = queue(); uint40 queueLength = _getQueueLength(queueRef); // Reserve some memory to save gas on hashing later on. This is a relatively safe estimate // for the average transaction size that will prevent having to resize this chunk of memory // later on. Saves gas. bytes memory hashMemory = new bytes((msg.data.length / totalElementsToAppend) * 2); // Initialize the array of canonical chain leaves that we will append. bytes32[] memory leaves = new bytes32[](totalElementsToAppend); // Each leaf index corresponds to a tx, either sequenced or enqueued. uint32 leafIndex = 0; // Counter for number of sequencer transactions appended so far. uint32 numSequencerTransactions = 0; // We will sequentially append leaves which are pointers to the queue. // The initial queue index is what is currently in storage. uint40 nextQueueIndex = getNextQueueIndex(); BatchContext memory curContext; for (uint32 i = 0; i < numContexts; i++) { BatchContext memory nextContext = _getBatchContext(i); if (i == 0) { // Execute a special check for the first batch. _validateFirstBatchContext(nextContext); } // Execute this check on every single batch, including the first one. _validateNextBatchContext( curContext, nextContext, nextQueueIndex, queueRef ); // Now we can update our current context. curContext = nextContext; // Process sequencer transactions first. for (uint32 j = 0; j < curContext.numSequencedTransactions; j++) { uint256 txDataLength; assembly { txDataLength := shr(232, calldataload(nextTransactionPtr)) } require( txDataLength <= MAX_ROLLUP_TX_SIZE, "Transaction data size exceeds maximum for rollup transaction." ); leaves[leafIndex] = _getSequencerLeafHash( curContext, nextTransactionPtr, txDataLength, hashMemory ); nextTransactionPtr += uint40(TX_DATA_HEADER_SIZE + txDataLength); numSequencerTransactions++; leafIndex++; } // Now process any subsequent queue transactions. for (uint32 j = 0; j < curContext.numSubsequentQueueTransactions; j++) { require( nextQueueIndex < queueLength, "Not enough queued transactions to append." ); leaves[leafIndex] = _getQueueLeafHash(nextQueueIndex); nextQueueIndex++; leafIndex++; } } _validateFinalBatchContext( curContext, nextQueueIndex, queueLength, queueRef ); require( msg.data.length == nextTransactionPtr, "Not all sequencer transactions were processed." ); require( leafIndex == totalElementsToAppend, "Actual transaction index does not match expected total elements to append." ); // Generate the required metadata that we need to append this batch uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions; uint40 blockTimestamp; uint40 blockNumber; if (curContext.numSubsequentQueueTransactions == 0) { // The last element is a sequencer tx, therefore pull timestamp and block number from // the last context. blockTimestamp = uint40(curContext.timestamp); blockNumber = uint40(curContext.blockNumber); } else { // The last element is a queue tx, therefore pull timestamp and block number from the // queue element. // curContext.numSubsequentQueueTransactions > 0 which means that we've processed at // least one queue element. We increment nextQueueIndex after processing each queue // element, so the index of the last element we processed is nextQueueIndex - 1. Lib_OVMCodec.QueueElement memory lastElement = _getQueueElement( nextQueueIndex - 1, queueRef ); blockTimestamp = lastElement.timestamp; blockNumber = lastElement.blockNumber; } // For efficiency reasons getMerkleRoot modifies the `leaves` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards _appendBatch( Lib_MerkleTree.getMerkleRoot(leaves), totalElementsToAppend, numQueuedTransactions, blockTimestamp, blockNumber ); emit SequencerBatchAppended( nextQueueIndex - numQueuedTransactions, numQueuedTransactions, getTotalElements() ); } /** * Verifies whether a transaction is included in the chain. * @param _transaction Transaction to verify. * @param _txChainElement Transaction chain element corresponding to the transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof Inclusion proof for the provided transaction chain element. * @return True if the transaction exists in the CTC, false if not. */ function verifyTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) override public view returns ( bool ) { if (_txChainElement.isSequenced == true) { return _verifySequencerTransaction( _transaction, _txChainElement, _batchHeader, _inclusionProof ); } else { return _verifyQueueTransaction( _transaction, _txChainElement.queueIndex, _batchHeader, _inclusionProof ); } } /********************** * Internal Functions * **********************/ /** * Returns the BatchContext located at a particular index. * @param _index The index of the BatchContext * @return The BatchContext at the specified index. */ function _getBatchContext( uint256 _index ) internal pure returns ( BatchContext memory ) { uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE; uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 ctxTimestamp; uint256 ctxBlockNumber; assembly { numSequencedTransactions := shr(232, calldataload(contextPtr)) numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3))) ctxTimestamp := shr(216, calldataload(add(contextPtr, 6))) ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11))) } return BatchContext({ numSequencedTransactions: numSequencedTransactions, numSubsequentQueueTransactions: numSubsequentQueueTransactions, timestamp: ctxTimestamp, blockNumber: ctxBlockNumber }); } /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Index of the next queue element. */ function _getBatchExtraData() internal view returns ( uint40, uint40, uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadata(); uint40 totalElements; uint40 nextQueueIndex; uint40 lastTimestamp; uint40 lastBlockNumber; // solhint-disable max-line-length assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000)) lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000)) lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000)) } // solhint-enable max-line-length return ( totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _nextQueueIndex Index of the next queue element. * @param _timestamp Timestamp for the last batch. * @param _blockNumber Block number of the last batch. * @return Encoded batch context. */ function _makeBatchExtraData( uint40 _totalElements, uint40 _nextQueueIndex, uint40 _timestamp, uint40 _blockNumber ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _nextQueueIndex)) extraData := or(extraData, shl(80, _timestamp)) extraData := or(extraData, shl(120, _blockNumber)) extraData := shl(40, extraData) } return extraData; } /** * Retrieves the hash of a queue element. * @param _index Index of the queue element to retrieve a hash for. * @return Hash of the queue element. */ function _getQueueLeafHash( uint256 _index ) internal pure returns ( bytes32 ) { return _hashTransactionChainElement( Lib_OVMCodec.TransactionChainElement({ isSequenced: false, queueIndex: _index, timestamp: 0, blockNumber: 0, txData: hex"" }) ); } /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function _getQueueElement( uint256 _index, iOVM_ChainStorageContainer _queueRef ) internal view returns ( Lib_OVMCodec.QueueElement memory _element ) { // The underlying queue data structure stores 2 elements // per insertion, so to get the actual desired queue index // we need to multiply by 2. uint40 trueIndex = uint40(_index * 2); bytes32 transactionHash = _queueRef.get(trueIndex); bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1); uint40 elementTimestamp; uint40 elementBlockNumber; // solhint-disable max-line-length assembly { elementTimestamp := and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } // solhint-enable max-line-length return Lib_OVMCodec.QueueElement({ transactionHash: transactionHash, timestamp: elementTimestamp, blockNumber: elementBlockNumber }); } /** * Retrieves the length of the queue. * @return Length of the queue. */ function _getQueueLength( iOVM_ChainStorageContainer _queueRef ) internal view returns ( uint40 ) { // The underlying queue data structure stores 2 elements // per insertion, so to get the real queue length we need // to divide by 2. return uint40(_queueRef.length() / 2); } /** * Retrieves the hash of a sequencer element. * @param _context Batch context for the given element. * @param _nextTransactionPtr Pointer to the next transaction in the calldata. * @param _txDataLength Length of the transaction item. * @return Hash of the sequencer element. */ function _getSequencerLeafHash( BatchContext memory _context, uint256 _nextTransactionPtr, uint256 _txDataLength, bytes memory _hashMemory ) internal pure returns ( bytes32 ) { // Only allocate more memory if we didn't reserve enough to begin with. if (BYTES_TILL_TX_DATA + _txDataLength > _hashMemory.length) { _hashMemory = new bytes(BYTES_TILL_TX_DATA + _txDataLength); } uint256 ctxTimestamp = _context.timestamp; uint256 ctxBlockNumber = _context.blockNumber; bytes32 leafHash; assembly { let chainElementStart := add(_hashMemory, 0x20) // Set the first byte equal to `1` to indicate this is a sequencer chain element. // This distinguishes sequencer ChainElements from queue ChainElements because // all queue ChainElements are ABI encoded and the first byte of ABI encoded // elements is always zero mstore8(chainElementStart, 1) mstore(add(chainElementStart, 1), ctxTimestamp) mstore(add(chainElementStart, 33), ctxBlockNumber) // solhint-disable-next-line max-line-length calldatacopy(add(chainElementStart, BYTES_TILL_TX_DATA), add(_nextTransactionPtr, 3), _txDataLength) leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, _txDataLength)) } return leafHash; } /** * Retrieves the hash of a sequencer element. * @param _txChainElement The chain element which is hashed to calculate the leaf. * @return Hash of the sequencer element. */ function _getSequencerLeafHash( Lib_OVMCodec.TransactionChainElement memory _txChainElement ) internal view returns( bytes32 ) { bytes memory txData = _txChainElement.txData; uint256 txDataLength = _txChainElement.txData.length; bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + txDataLength); uint256 ctxTimestamp = _txChainElement.timestamp; uint256 ctxBlockNumber = _txChainElement.blockNumber; bytes32 leafHash; assembly { let chainElementStart := add(chainElement, 0x20) // Set the first byte equal to `1` to indicate this is a sequencer chain element. // This distinguishes sequencer ChainElements from queue ChainElements because // all queue ChainElements are ABI encoded and the first byte of ABI encoded // elements is always zero mstore8(chainElementStart, 1) mstore(add(chainElementStart, 1), ctxTimestamp) mstore(add(chainElementStart, 33), ctxBlockNumber) // solhint-disable-next-line max-line-length pop(staticcall(gas(), 0x04, add(txData, 0x20), txDataLength, add(chainElementStart, BYTES_TILL_TX_DATA), txDataLength)) leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, txDataLength)) } return leafHash; } /** * Inserts a batch into the chain of batches. * @param _transactionRoot Root of the transaction tree for this batch. * @param _batchSize Number of elements in the batch. * @param _numQueuedTransactions Number of queue transactions in the batch. * @param _timestamp The latest batch timestamp. * @param _blockNumber The latest batch blockNumber. */ function _appendBatch( bytes32 _transactionRoot, uint256 _batchSize, uint256 _numQueuedTransactions, uint40 _timestamp, uint40 _blockNumber ) internal { iOVM_ChainStorageContainer batchesRef = batches(); (uint40 totalElements, uint40 nextQueueIndex,,) = _getBatchExtraData(); Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({ batchIndex: batchesRef.length(), batchRoot: _transactionRoot, batchSize: _batchSize, prevTotalElements: totalElements, extraData: hex"" }); emit TransactionBatchAppended( header.batchIndex, header.batchRoot, header.batchSize, header.prevTotalElements, header.extraData ); bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header); bytes27 latestBatchContext = _makeBatchExtraData( totalElements + uint40(header.batchSize), nextQueueIndex + uint40(_numQueuedTransactions), _timestamp, _blockNumber ); batchesRef.push(batchHeaderHash, latestBatchContext); } /** * Checks that the first batch context in a sequencer submission is valid * @param _firstContext The batch context to validate. */ function _validateFirstBatchContext( BatchContext memory _firstContext ) internal view { // If there are existing elements, this batch must have the same context // or a later timestamp and block number. if (getTotalElements() > 0) { (,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData(); require( _firstContext.blockNumber >= lastBlockNumber, "Context block number is lower than last submitted." ); require( _firstContext.timestamp >= lastTimestamp, "Context timestamp is lower than last submitted." ); } // Sequencer cannot submit contexts which are more than the force inclusion period old. require( _firstContext.timestamp + forceInclusionPeriodSeconds >= block.timestamp, "Context timestamp too far in the past." ); require( _firstContext.blockNumber + forceInclusionPeriodBlocks >= block.number, "Context block number too far in the past." ); } /** * Checks that a given batch context has a time context which is below a given que element * @param _context The batch context to validate has values lower. * @param _queueIndex Index of the queue element we are validating came later than the context. * @param _queueRef The storage container for the queue. */ function _validateContextBeforeEnqueue( BatchContext memory _context, uint40 _queueIndex, iOVM_ChainStorageContainer _queueRef ) internal view { Lib_OVMCodec.QueueElement memory nextQueueElement = _getQueueElement( _queueIndex, _queueRef ); // If the force inclusion period has passed for an enqueued transaction, it MUST be the // next chain element. require( block.timestamp < nextQueueElement.timestamp + forceInclusionPeriodSeconds, // solhint-disable-next-line max-line-length "Previously enqueued batches have expired and must be appended before a new sequencer batch." ); // Just like sequencer transaction times must be increasing relative to each other, // We also require that they be increasing relative to any interspersed queue elements. require( _context.timestamp <= nextQueueElement.timestamp, "Sequencer transaction timestamp exceeds that of next queue element." ); require( _context.blockNumber <= nextQueueElement.blockNumber, "Sequencer transaction blockNumber exceeds that of next queue element." ); } /** * Checks that a given batch context is valid based on its previous context, and the next queue * elemtent. * @param _prevContext The previously validated batch context. * @param _nextContext The batch context to validate with this call. * @param _nextQueueIndex Index of the next queue element to process for the _nextContext's * subsequentQueueElements. * @param _queueRef The storage container for the queue. */ function _validateNextBatchContext( BatchContext memory _prevContext, BatchContext memory _nextContext, uint40 _nextQueueIndex, iOVM_ChainStorageContainer _queueRef ) internal view { // All sequencer transactions' times must be greater than or equal to the previous ones. require( _nextContext.timestamp >= _prevContext.timestamp, "Context timestamp values must monotonically increase." ); require( _nextContext.blockNumber >= _prevContext.blockNumber, "Context blockNumber values must monotonically increase." ); // If there is going to be a queue element pulled in from this context: if (_nextContext.numSubsequentQueueTransactions > 0) { _validateContextBeforeEnqueue( _nextContext, _nextQueueIndex, _queueRef ); } } /** * Checks that the final batch context in a sequencer submission is valid. * @param _finalContext The batch context to validate. * @param _queueLength The length of the queue at the start of the batchAppend call. * @param _nextQueueIndex The next element in the queue that will be pulled into the CTC. * @param _queueRef The storage container for the queue. */ function _validateFinalBatchContext( BatchContext memory _finalContext, uint40 _nextQueueIndex, uint40 _queueLength, iOVM_ChainStorageContainer _queueRef ) internal view { // If the queue is not now empty, check the mononoticity of whatever the next batch that // will come in is. if (_queueLength - _nextQueueIndex > 0 && _finalContext.numSubsequentQueueTransactions == 0) { _validateContextBeforeEnqueue( _finalContext, _nextQueueIndex, _queueRef ); } // Batches cannot be added from the future, or subsequent enqueue() contexts would violate // monotonicity. require(_finalContext.timestamp <= block.timestamp, "Context timestamp is from the future."); require(_finalContext.blockNumber <= block.number, "Context block number is from the future."); } /** * Hashes a transaction chain element. * @param _element Chain element to hash. * @return Hash of the chain element. */ function _hashTransactionChainElement( Lib_OVMCodec.TransactionChainElement memory _element ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _element.isSequenced, _element.queueIndex, _element.timestamp, _element.blockNumber, _element.txData ) ); } /** * Verifies a sequencer transaction, returning true if it was indeed included in the CTC * @param _transaction The transaction we are verifying inclusion of. * @param _txChainElement The chain element that the transaction is claimed to be a part of. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof An inclusion proof into the CTC at a particular index. * @return True if the transaction was included in the specified location, else false. */ function _verifySequencerTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) internal view returns ( bool ) { OVM_ExecutionManager ovmExecutionManager = OVM_ExecutionManager(resolve("OVM_ExecutionManager")); uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit(); bytes32 leafHash = _getSequencerLeafHash(_txChainElement); require( _verifyElement( leafHash, _batchHeader, _inclusionProof ), "Invalid Sequencer transaction inclusion proof." ); require( _transaction.blockNumber == _txChainElement.blockNumber && _transaction.timestamp == _txChainElement.timestamp && _transaction.entrypoint == resolve("OVM_DecompressionPrecompileAddress") && _transaction.gasLimit == gasLimit && _transaction.l1TxOrigin == address(0) && _transaction.l1QueueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE && keccak256(_transaction.data) == keccak256(_txChainElement.txData), "Invalid Sequencer transaction." ); return true; } /** * Verifies a queue transaction, returning true if it was indeed included in the CTC * @param _transaction The transaction we are verifying inclusion of. * @param _queueIndex The queueIndex of the queued transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to * queue tx). * @return True if the transaction was included in the specified location, else false. */ function _verifyQueueTransaction( Lib_OVMCodec.Transaction memory _transaction, uint256 _queueIndex, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) internal view returns ( bool ) { bytes32 leafHash = _getQueueLeafHash(_queueIndex); require( _verifyElement( leafHash, _batchHeader, _inclusionProof ), "Invalid Queue transaction inclusion proof." ); bytes32 transactionHash = keccak256( abi.encode( _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ) ); Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex); require( el.transactionHash == transactionHash && el.timestamp == _transaction.timestamp && el.blockNumber == _transaction.blockNumber, "Invalid Queue transaction." ); return true; } /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function _verifyElement( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) internal view returns ( bool ) { require( Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(uint32(_batchHeader.batchIndex)), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Interface Imports */ import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /* Contract Imports */ import { OVM_DeployerWhitelist } from "../predeploys/OVM_DeployerWhitelist.sol"; /* External Imports */ import { Math } from "@openzeppelin/contracts/math/Math.sol"; /** * @title OVM_ExecutionManager * @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed * environment allowing us to execute OVM transactions deterministically on either Layer 1 or * Layer 2. * The EM's run() function is the first function called during the execution of any * transaction on L2. * For each context-dependent EVM operation the EM has a function which implements a corresponding * OVM operation, which will read state from the State Manager contract. * The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any * context-dependent operations. * * Compiler used: solc * Runtime target: EVM */ contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver { /******************************** * External Contract References * ********************************/ iOVM_SafetyChecker internal ovmSafetyChecker; iOVM_StateManager internal ovmStateManager; /******************************* * Execution Context Variables * *******************************/ GasMeterConfig internal gasMeterConfig; GlobalContext internal globalContext; TransactionContext internal transactionContext; MessageContext internal messageContext; TransactionRecord internal transactionRecord; MessageRecord internal messageRecord; /************************** * Gas Metering Constants * **************************/ address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5; uint256 constant NUISANCE_GAS_SLOAD = 20000; uint256 constant NUISANCE_GAS_SSTORE = 20000; uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000; uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100; uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000; /************************** * Native Value Constants * **************************/ // Public so we can access and make assertions in integration tests. uint256 public constant CALL_WITH_VALUE_INTRINSIC_GAS = 90000; /************************** * Default Context Values * **************************/ uint256 constant DEFAULT_UINT256 = 0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d; address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0; /************************************* * Container Contract Address Prefix * *************************************/ /** * @dev The Execution Manager and State Manager each have this 30 byte prefix, * and are uncallable. */ address constant CONTAINER_CONTRACT_PREFIX = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, GasMeterConfig memory _gasMeterConfig, GlobalContext memory _globalContext ) Lib_AddressResolver(_libAddressManager) { ovmSafetyChecker = iOVM_SafetyChecker(resolve("OVM_SafetyChecker")); gasMeterConfig = _gasMeterConfig; globalContext = _globalContext; _resetContext(); } /********************** * Function Modifiers * **********************/ /** * Applies dynamically-sized refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of the ovmOPCODE is fixed. * @param _cost Desired gas cost for the function after the refund. */ modifier netGasCost( uint256 _cost ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund everything *except* the specified cost. if (_cost < gasUsed) { transactionRecord.ovmGasRefund += gasUsed - _cost; } } /** * Applies a fixed-size gas refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered. * @param _discount Amount of gas cost to refund for the ovmOPCODE. */ modifier fixedGasDiscount( uint256 _discount ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund the specified _discount, unless this risks underflow. if (_discount < gasUsed) { transactionRecord.ovmGasRefund += _discount; } else { // refund all we can without risking underflow. transactionRecord.ovmGasRefund += gasUsed; } } /** * Makes sure we're not inside a static context. */ modifier notStatic() { if (messageContext.isStatic == true) { _revertWithFlag(RevertFlag.STATIC_VIOLATION); } _; } /************************************ * Transaction Execution Entrypoint * ************************************/ /** * Starts the execution of a transaction via the OVM_ExecutionManager. * @param _transaction Transaction data to be executed. * @param _ovmStateManager iOVM_StateManager implementation providing account state. */ function run( Lib_OVMCodec.Transaction memory _transaction, address _ovmStateManager ) override external returns ( bytes memory ) { // Make sure that run() is not re-enterable. This condition should always be satisfied // Once run has been called once, due to the behavior of _isValidInput(). if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return bytes(""); } // Store our OVM_StateManager instance (significantly easier than attempting to pass the // address around in calldata). ovmStateManager = iOVM_StateManager(_ovmStateManager); // Make sure this function can't be called by anyone except the owner of the // OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because // this would make the `run` itself invalid. require( // This method may return false during fraud proofs, but always returns true in // L2 nodes' State Manager precompile. ovmStateManager.isAuthenticated(msg.sender), "Only authenticated addresses in ovmStateManager can call this function" ); // Initialize the execution context, must be initialized before we perform any gas metering // or we'll throw a nuisance gas error. _initContext(_transaction); // TEMPORARY: Gas metering is disabled for minnet. // // Check whether we need to start a new epoch, do so if necessary. // _checkNeedsNewEpoch(_transaction.timestamp); // Make sure the transaction's gas limit is valid. We don't revert here because we reserve // reverts for INVALID_STATE_ACCESS. if (_isValidInput(_transaction) == false) { _resetContext(); return bytes(""); } // TEMPORARY: Gas metering is disabled for minnet. // // Check gas right before the call to get total gas consumed by OVM transaction. // uint256 gasProvided = gasleft(); // Run the transaction, make sure to meter the gas usage. (, bytes memory returndata) = ovmCALL( _transaction.gasLimit - gasMeterConfig.minTransactionGasLimit, _transaction.entrypoint, 0, _transaction.data ); // TEMPORARY: Gas metering is disabled for minnet. // // Update the cumulative gas based on the amount of gas used. // uint256 gasUsed = gasProvided - gasleft(); // _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin); // Wipe the execution context. _resetContext(); return returndata; } /****************************** * Opcodes: Execution Context * ******************************/ /** * @notice Overrides CALLER. * @return _CALLER Address of the CALLER within the current message context. */ function ovmCALLER() override external view returns ( address _CALLER ) { return messageContext.ovmCALLER; } /** * @notice Overrides ADDRESS. * @return _ADDRESS Active ADDRESS within the current message context. */ function ovmADDRESS() override public view returns ( address _ADDRESS ) { return messageContext.ovmADDRESS; } /** * @notice Overrides CALLVALUE. * @return _CALLVALUE Value sent along with the call according to the current message context. */ function ovmCALLVALUE() override public view returns ( uint256 _CALLVALUE ) { return messageContext.ovmCALLVALUE; } /** * @notice Overrides TIMESTAMP. * @return _TIMESTAMP Value of the TIMESTAMP within the transaction context. */ function ovmTIMESTAMP() override external view returns ( uint256 _TIMESTAMP ) { return transactionContext.ovmTIMESTAMP; } /** * @notice Overrides NUMBER. * @return _NUMBER Value of the NUMBER within the transaction context. */ function ovmNUMBER() override external view returns ( uint256 _NUMBER ) { return transactionContext.ovmNUMBER; } /** * @notice Overrides GASLIMIT. * @return _GASLIMIT Value of the block's GASLIMIT within the transaction context. */ function ovmGASLIMIT() override external view returns ( uint256 _GASLIMIT ) { return transactionContext.ovmGASLIMIT; } /** * @notice Overrides CHAINID. * @return _CHAINID Value of the chain's CHAINID within the global context. */ function ovmCHAINID() override external view returns ( uint256 _CHAINID ) { return globalContext.ovmCHAINID; } /********************************* * Opcodes: L2 Execution Context * *********************************/ /** * @notice Specifies from which source (Sequencer or Queue) this transaction originated from. * @return _queueOrigin Enum indicating the ovmL1QUEUEORIGIN within the current message context. */ function ovmL1QUEUEORIGIN() override external view returns ( Lib_OVMCodec.QueueOrigin _queueOrigin ) { return transactionContext.ovmL1QUEUEORIGIN; } /** * @notice Specifies which L1 account, if any, sent this transaction by calling enqueue(). * @return _l1TxOrigin Address of the account which sent the tx into L2 from L1. */ function ovmL1TXORIGIN() override external view returns ( address _l1TxOrigin ) { return transactionContext.ovmL1TXORIGIN; } /******************** * Opcodes: Halting * ********************/ /** * @notice Overrides REVERT. * @param _data Bytes data to pass along with the REVERT. */ function ovmREVERT( bytes memory _data ) override public { _revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data); } /****************************** * Opcodes: Contract Creation * ******************************/ /** * @notice Overrides CREATE. * @param _bytecode Code to be used to CREATE a new contract. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE( bytes memory _bytecode ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE address. address contractAddress = Lib_EthUtils.getAddressForCREATE( creator, _getAccountNonce(creator) ); return _createContract( contractAddress, _bytecode, MessageType.ovmCREATE ); } /** * @notice Overrides CREATE2. * @param _bytecode Code to be used to CREATE2 a new contract. * @param _salt Value used to determine the contract's address. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE2( bytes memory _bytecode, bytes32 _salt ) override external notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE2 address. address contractAddress = Lib_EthUtils.getAddressForCREATE2( creator, _bytecode, _salt ); return _createContract( contractAddress, _bytecode, MessageType.ovmCREATE2 ); } /******************************* * Account Abstraction Opcodes * ******************************/ /** * Retrieves the nonce of the current ovmADDRESS. * @return _nonce Nonce of the current contract. */ function ovmGETNONCE() override external returns ( uint256 _nonce ) { return _getAccountNonce(ovmADDRESS()); } /** * Bumps the nonce of the current ovmADDRESS by one. */ function ovmINCREMENTNONCE() override external notStatic { address account = ovmADDRESS(); uint256 nonce = _getAccountNonce(account); // Prevent overflow. if (nonce + 1 > nonce) { _setAccountNonce(account, nonce + 1); } } /** * Creates a new EOA contract account, for account abstraction. * @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks * because the contract we're creating is trusted (no need to do safety checking or to * handle unexpected reverts). Doesn't need to return an address because the address is * assumed to be the user's actual address. * @param _messageHash Hash of a message signed by some user, for verification. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) override public notStatic { // Recover the EOA address from the message hash and signature parameters. Since we do the // hashing in advance, we don't have handle different message hashing schemes. Even if this // function were to return the wrong address (rather than explicitly returning the zero // address), the rest of the transaction would simply fail (since there's no EOA account to // actually execute the transaction). address eoa = ecrecover( _messageHash, _v + 27, _r, _s ); // Invalid signature is a case we proactively handle with a revert. We could alternatively // have this function return a `success` boolean, but this is just easier. if (eoa == address(0)) { ovmREVERT(bytes("Signature provided for EOA contract creation is invalid.")); } // If the user already has an EOA account, then there's no need to perform this operation. if (_hasEmptyAccount(eoa) == false) { return; } // We always need to initialize the contract with the default account values. _initPendingAccount(eoa); // Temporarily set the current address so it's easier to access on L2. address prevADDRESS = messageContext.ovmADDRESS; messageContext.ovmADDRESS = eoa; // Creates a duplicate of the OVM_ProxyEOA located at 0x42....09. Uses the following // "magic" prefix to deploy an exact copy of the code: // PUSH1 0x0D # size of this prefix in bytes // CODESIZE // SUB # subtract prefix size from codesize // DUP1 // PUSH1 0x0D // PUSH1 0x00 // CODECOPY # copy everything after prefix into memory at pos 0 // PUSH1 0x00 // RETURN # return the copied code address proxyEOA = Lib_EthUtils.createContract(abi.encodePacked( hex"600D380380600D6000396000f3", ovmEXTCODECOPY( Lib_PredeployAddresses.PROXY_EOA, 0, ovmEXTCODESIZE(Lib_PredeployAddresses.PROXY_EOA) ) )); // Reset the address now that we're done deploying. messageContext.ovmADDRESS = prevADDRESS; // Commit the account with its final values. _commitPendingAccount( eoa, address(proxyEOA), keccak256(Lib_EthUtils.getCode(address(proxyEOA))) ); _setAccountNonce(eoa, 0); } /********************************* * Opcodes: Contract Interaction * *********************************/ /** * @notice Overrides CALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) override public fixedGasDiscount(100000) returns ( bool _success, bytes memory _returndata ) { // CALL updates the CALLER and ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.ovmCALLVALUE = _value; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmCALL ); } /** * @notice Overrides STATICCALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmSTATICCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(80000) returns ( bool _success, bytes memory _returndata ) { // STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static, // valueless context. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; nextMessageContext.ovmCALLVALUE = 0; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmSTATICCALL ); } /** * @notice Overrides DELEGATECALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmDELEGATECALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(40000) returns ( bool _success, bytes memory _returndata ) { // DELEGATECALL does not change anything about the message context. MessageContext memory nextMessageContext = messageContext; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmDELEGATECALL ); } /** * @notice Legacy ovmCALL function which did not support ETH value; this maintains backwards * compatibility. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public returns( bool _success, bytes memory _returndata ) { // Legacy ovmCALL assumed always-0 value. return ovmCALL( _gasLimit, _address, 0, _calldata ); } /************************************ * Opcodes: Contract Storage Access * ************************************/ /** * @notice Overrides SLOAD. * @param _key 32 byte key of the storage slot to load. * @return _value 32 byte value of the requested storage slot. */ function ovmSLOAD( bytes32 _key ) override external netGasCost(40000) returns ( bytes32 _value ) { // We always SLOAD from the storage of ADDRESS. address contractAddress = ovmADDRESS(); return _getContractStorage( contractAddress, _key ); } /** * @notice Overrides SSTORE. * @param _key 32 byte key of the storage slot to set. * @param _value 32 byte value for the storage slot. */ function ovmSSTORE( bytes32 _key, bytes32 _value ) override external notStatic netGasCost(60000) { // We always SSTORE to the storage of ADDRESS. address contractAddress = ovmADDRESS(); _putContractStorage( contractAddress, _key, _value ); } /********************************* * Opcodes: Contract Code Access * *********************************/ /** * @notice Overrides EXTCODECOPY. * @param _contract Address of the contract to copy code from. * @param _offset Offset in bytes from the start of contract code to copy beyond. * @param _length Total number of bytes to copy from the contract's code. * @return _code Bytes of code copied from the requested contract. */ function ovmEXTCODECOPY( address _contract, uint256 _offset, uint256 _length ) override public returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _getAccountEthAddress(_contract), _offset, _length ); } /** * @notice Overrides EXTCODESIZE. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function ovmEXTCODESIZE( address _contract ) override public returns ( uint256 _EXTCODESIZE ) { return Lib_EthUtils.getCodeSize( _getAccountEthAddress(_contract) ); } /** * @notice Overrides EXTCODEHASH. * @param _contract Address of the contract to query the hash of. * @return _EXTCODEHASH Hash of the requested contract. */ function ovmEXTCODEHASH( address _contract ) override external returns ( bytes32 _EXTCODEHASH ) { return Lib_EthUtils.getCodeHash( _getAccountEthAddress(_contract) ); } /*************************************** * Public Functions: ETH Value Opcodes * ***************************************/ /** * @notice Overrides BALANCE. * NOTE: In the future, this could be optimized to directly invoke EM._getContractStorage(...). * @param _contract Address of the contract to query the OVM_ETH balance of. * @return _BALANCE OVM_ETH balance of the requested contract. */ function ovmBALANCE( address _contract ) override public returns ( uint256 _BALANCE ) { // Easiest way to get the balance is query OVM_ETH as normal. bytes memory balanceOfCalldata = abi.encodeWithSignature( "balanceOf(address)", _contract ); // Static call because this should be a read-only query. (bool success, bytes memory returndata) = ovmSTATICCALL( gasleft(), Lib_PredeployAddresses.OVM_ETH, balanceOfCalldata ); // All balanceOf queries should successfully return a uint, otherwise this must be an OOG. if (!success || returndata.length != 32) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // Return the decoded balance. return abi.decode(returndata, (uint256)); } /** * @notice Overrides SELFBALANCE. * @return _BALANCE OVM_ETH balance of the requesting contract. */ function ovmSELFBALANCE() override external returns ( uint256 _BALANCE ) { return ovmBALANCE(ovmADDRESS()); } /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view override returns ( uint256 _maxTransactionGasLimit ) { return gasMeterConfig.maxTransactionGasLimit; } /******************************************** * Public Functions: Deployment Whitelisting * ********************************************/ /** * Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2, * and reverts if not. * @param _deployerAddress Address attempting to deploy a contract. */ function _checkDeployerAllowed( address _deployerAddress ) internal { // From an OVM semantics perspective, this will appear identical to // the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to. (bool success, bytes memory data) = ovmSTATICCALL( gasleft(), Lib_PredeployAddresses.DEPLOYER_WHITELIST, abi.encodeWithSelector( OVM_DeployerWhitelist.isDeployerAllowed.selector, _deployerAddress ) ); bool isAllowed = abi.decode(data, (bool)); if (!isAllowed || !success) { _revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED); } } /******************************************** * Internal Functions: Contract Interaction * ********************************************/ /** * Creates a new contract and associates it with some contract address. * @param _contractAddress Address to associate the created contract with. * @param _bytecode Bytecode to be used to create the contract. * @return Final OVM contract address. * @return Revertdata, if and only if the creation threw an exception. */ function _createContract( address _contractAddress, bytes memory _bytecode, MessageType _messageType ) internal returns ( address, bytes memory ) { // We always update the nonce of the creating account, even if the creation fails. _setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1); // We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point // to the contract's associated address and CALLER to point to the previous ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = messageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _contractAddress; // Run the common logic which occurs between call-type and create-type messages, // passing in the creation bytecode and `true` to trigger create-specific logic. (bool success, bytes memory data) = _handleExternalMessage( nextMessageContext, gasleft(), _contractAddress, _bytecode, _messageType ); // Yellow paper requires that address returned is zero if the contract deployment fails. return ( success ? _contractAddress : address(0), data ); } /** * Calls the deployed contract associated with a given address. * @param _nextMessageContext Message context to be used for the call. * @param _gasLimit Amount of gas to be passed into this call. * @param _contract OVM address to be called. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function _callContract( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _calldata, MessageType _messageType ) internal returns ( bool _success, bytes memory _returndata ) { // We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2 // geth. So, we block calls to these addresses since they are not safe to run as an OVM // contract itself. if ( (uint256(_contract) & uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000)) == uint256(CONTAINER_CONTRACT_PREFIX) ) { // solhint-disable-next-line max-line-length // EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604 return (true, hex''); } // Both 0x0000... and the EVM precompiles have the same address on L1 and L2 --> // no trie lookup needed. address codeContractAddress = uint(_contract) < 100 ? _contract : _getAccountEthAddress(_contract); return _handleExternalMessage( _nextMessageContext, _gasLimit, codeContractAddress, _calldata, _messageType ); } /** * Handles all interactions which involve the execution manager calling out to untrusted code * (both calls and creates). Ensures that OVM-related measures are enforced, including L2 gas * refunds, nuisance gas, and flagged reversions. * * @param _nextMessageContext Message context to be used for the external message. * @param _gasLimit Amount of gas to be passed into this message. NOTE: this argument is * overwritten in some cases to avoid stack-too-deep. * @param _contract OVM address being called or deployed to * @param _data Data for the message (either calldata or creation code) * @param _messageType What type of ovmOPCODE this message corresponds to. * @return Whether or not the message (either a call or deployment) succeeded. * @return Data returned by the message. */ function _handleExternalMessage( MessageContext memory _nextMessageContext, // NOTE: this argument is overwritten in some cases to avoid stack-too-deep. uint256 _gasLimit, address _contract, bytes memory _data, MessageType _messageType ) internal returns ( bool, bytes memory ) { uint256 messageValue = _nextMessageContext.ovmCALLVALUE; // If there is value in this message, we need to transfer the ETH over before switching // contexts. if ( messageValue > 0 && _isValueType(_messageType) ) { // Handle out-of-intrinsic gas consistent with EVM behavior -- the subcall "appears to // revert" if we don't have enough gas to transfer the ETH. // Similar to dynamic gas cost of value exceeding gas here: // solhint-disable-next-line max-line-length // https://github.com/ethereum/go-ethereum/blob/c503f98f6d5e80e079c1d8a3601d188af2a899da/core/vm/interpreter.go#L268-L273 if (gasleft() < CALL_WITH_VALUE_INTRINSIC_GAS) { return (false, hex""); } // If there *is* enough gas to transfer ETH, then we need to make sure this amount of // gas is reserved (i.e. not given to the _contract.call below) to guarantee that // _handleExternalMessage can't run out of gas. In particular, in the event that // the call fails, we will need to transfer the ETH back to the sender. // Taking the lesser of _gasLimit and gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // guarantees that the second _attemptForcedEthTransfer below, if needed, always has // enough gas to succeed. _gasLimit = Math.min( _gasLimit, gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // Cannot overflow due to the above check. ); // Now transfer the value of the call. // The target is interpreted to be the next message's ovmADDRESS account. bool transferredOvmEth = _attemptForcedEthTransfer( _nextMessageContext.ovmADDRESS, messageValue ); // If the ETH transfer fails (should only be possible in the case of insufficient // balance), then treat this as a revert. This mirrors EVM behavior, see // solhint-disable-next-line max-line-length // https://github.com/ethereum/go-ethereum/blob/2dee31930c9977af2a9fcb518fb9838aa609a7cf/core/vm/evm.go#L298 if (!transferredOvmEth) { return (false, hex""); } } // We need to switch over to our next message context for the duration of this call. MessageContext memory prevMessageContext = messageContext; _switchMessageContext(prevMessageContext, _nextMessageContext); // Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs // expensive by touching a lot of different accounts or storage slots. Since most contracts // only use a few storage slots during any given transaction, this shouldn't be a limiting // factor. uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft; uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit); messageRecord.nuisanceGasLeft = nuisanceGasLimit; // Make the call and make sure to pass in the gas limit. Another instance of hidden // complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert // behavior can be controlled. In particular, we enforce that flags are passed through // revert data as to retrieve execution metadata that would normally be reverted out of // existence. bool success; bytes memory returndata; if (_isCreateType(_messageType)) { // safeCREATE() is a function which replicates a CREATE message, but uses return values // Which match that of CALL (i.e. bool, bytes). This allows many security checks to be // to be shared between untrusted call and create call frames. (success, returndata) = address(this).call{gas: _gasLimit}( abi.encodeWithSelector( this.safeCREATE.selector, _data, _contract ) ); } else { (success, returndata) = _contract.call{gas: _gasLimit}(_data); } // If the message threw an exception, its value should be returned back to the sender. // So, we force it back, BEFORE returning the messageContext to the previous addresses. // This operation is part of the reason we "reserved the intrinsic gas" above. if ( messageValue > 0 && _isValueType(_messageType) && !success ) { bool transferredOvmEth = _attemptForcedEthTransfer( prevMessageContext.ovmADDRESS, messageValue ); // Since we transferred it in above and the call reverted, the transfer back should // always pass. This code path should NEVER be triggered since we sent `messageValue` // worth of OVM_ETH into the target and reserved sufficient gas to execute the transfer, // but in case there is some edge case which has been missed, we revert the entire frame // (and its parent) to make sure the ETH gets sent back. if (!transferredOvmEth) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } } // Switch back to the original message context now that we're out of the call and all // OVM_ETH is in the right place. _switchMessageContext(_nextMessageContext, prevMessageContext); // Assuming there were no reverts, the message record should be accurate here. We'll update // this value in the case of a revert. uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft; // Reverts at this point are completely OK, but we need to make a few updates based on the // information passed through the revert. if (success == false) { ( RevertFlag flag, uint256 nuisanceGasLeftPostRevert, uint256 ovmGasRefund, bytes memory returndataFromFlag ) = _decodeRevertData(returndata); // INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the // parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must // halt any further transaction execution that could impact the execution result. if (flag == RevertFlag.INVALID_STATE_ACCESS) { _revertWithFlag(flag); } // INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't // dependent on the input state, so we can just handle them like standard reverts. // Our only change here is to record the gas refund reported by the call (enforced by // safety checking). if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE || flag == RevertFlag.STATIC_VIOLATION || flag == RevertFlag.CREATOR_NOT_ALLOWED ) { transactionRecord.ovmGasRefund = ovmGasRefund; } // INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the // flag, *not* the full encoded flag. Additionally, we surface custom error messages // to developers in the case of unsafe creations for improved devex. // All other revert types return no data. if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE ) { returndata = returndataFromFlag; } else { returndata = hex''; } // Reverts mean we need to use up whatever "nuisance gas" was used by the call. // EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message // to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they // run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags // will simply pass up the remaining nuisance gas. nuisanceGasLeft = nuisanceGasLeftPostRevert; } // We need to reset the nuisance gas back to its original value minus the amount used here. messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft); return ( success, returndata ); } /** * Handles the creation-specific safety measures required for OVM contract deployment. * This function sanitizes the return types for creation messages to match calls (bool, bytes), * by being an external function which the EM can call, that mimics the success/fail case of the * CREATE. * This allows for consistent handling of both types of messages in _handleExternalMessage(). * Having this step occur as a separate call frame also allows us to easily revert the * contract deployment in the event that the code is unsafe. * * @param _creationCode Code to pass into CREATE for deployment. * @param _address OVM address being deployed to. */ function safeCREATE( bytes memory _creationCode, address _address ) external { // The only way this should callable is from within _createContract(), // and it should DEFINITELY not be callable by a non-EM code contract. if (msg.sender != address(this)) { return; } // Check that there is not already code at this address. if (_hasEmptyAccount(_address) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.CREATE_COLLISION ); } // Check the creation bytecode against the OVM_SafetyChecker. if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, // solhint-disable-next-line max-line-length Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?") ); } // We always need to initialize the contract with the default account values. _initPendingAccount(_address); // Actually execute the EVM create message. // NOTE: The inline assembly below means we can NOT make any evm calls between here and then address ethAddress = Lib_EthUtils.createContract(_creationCode); if (ethAddress == address(0)) { // If the creation fails, the EVM lets us grab its revert data. This may contain a // revert flag to be used above in _handleExternalMessage, so we pass the revert data // back up unmodified. assembly { returndatacopy(0,0,returndatasize()) revert(0, returndatasize()) } } // Again simply checking that the deployed code is safe too. Contracts can generate // arbitrary deployment code, so there's no easy way to analyze this beforehand. bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress); if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, // solhint-disable-next-line max-line-length Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.") ); } // Contract creation didn't need to be reverted and the bytecode is safe. We finish up by // associating the desired address with the newly created contract's code hash and address. _commitPendingAccount( _address, ethAddress, Lib_EthUtils.getCodeHash(ethAddress) ); } /****************************************** * Internal Functions: Value Manipulation * ******************************************/ /** * Invokes an ovmCALL to OVM_ETH.transfer on behalf of the current ovmADDRESS, allowing us to * force movement of OVM_ETH in correspondence with ETH's native value functionality. * WARNING: this will send on behalf of whatever the messageContext.ovmADDRESS is in storage * at the time of the call. * NOTE: In the future, this could be optimized to directly invoke EM._setContractStorage(...). * @param _to Amount of OVM_ETH to be sent. * @param _value Amount of OVM_ETH to send. * @return _success Whether or not the transfer worked. */ function _attemptForcedEthTransfer( address _to, uint256 _value ) internal returns( bool _success ) { bytes memory transferCalldata = abi.encodeWithSignature( "transfer(address,uint256)", _to, _value ); // OVM_ETH inherits from the UniswapV2ERC20 standard. In this implementation, its return // type is a boolean. However, the implementation always returns true if it does not revert // Thus, success of the call frame is sufficient to infer success of the transfer itself. (bool success, ) = ovmCALL( gasleft(), Lib_PredeployAddresses.OVM_ETH, 0, transferCalldata ); return success; } /****************************************** * Internal Functions: State Manipulation * ******************************************/ /** * Checks whether an account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account exists. */ function _hasAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasAccount(_address); } /** * Checks whether a known empty account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account empty exists. */ function _hasEmptyAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasEmptyAccount(_address); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function _setAccountNonce( address _address, uint256 _nonce ) internal { _checkAccountChange(_address); ovmStateManager.setAccountNonce(_address, _nonce); } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return _nonce Nonce of the account. */ function _getAccountNonce( address _address ) internal returns ( uint256 _nonce ) { _checkAccountLoad(_address); return ovmStateManager.getAccountNonce(_address); } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return _ethAddress Corresponding Ethereum address. */ function _getAccountEthAddress( address _address ) internal returns ( address _ethAddress ) { _checkAccountLoad(_address); return ovmStateManager.getAccountEthAddress(_address); } /** * Creates the default account object for the given address. * @param _address Address of the account create. */ function _initPendingAccount( address _address ) internal { // Although it seems like `_checkAccountChange` would be more appropriate here, we don't // actually consider an account "changed" until it's inserted into the state (in this case // by `_commitPendingAccount`). _checkAccountLoad(_address); ovmStateManager.initPendingAccount(_address); } /** * Stores additional relevant data for a new account, thereby "committing" it to the state. * This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract * creation. * @param _address Address of the account to commit. * @param _ethAddress Address of the associated deployed contract. * @param _codeHash Hash of the code stored at the address. */ function _commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) internal { _checkAccountChange(_address); ovmStateManager.commitPendingAccount( _address, _ethAddress, _codeHash ); } /** * Retrieves the value of a storage slot. * @param _contract Address of the contract to query. * @param _key 32 byte key of the storage slot. * @return _value 32 byte storage slot value. */ function _getContractStorage( address _contract, bytes32 _key ) internal returns ( bytes32 _value ) { _checkContractStorageLoad(_contract, _key); return ovmStateManager.getContractStorage(_contract, _key); } /** * Sets the value of a storage slot. * @param _contract Address of the contract to modify. * @param _key 32 byte key of the storage slot. * @param _value 32 byte storage slot value. */ function _putContractStorage( address _contract, bytes32 _key, bytes32 _value ) internal { // We don't set storage if the value didn't change. Although this acts as a convenient // optimization, it's also necessary to avoid the case in which a contract with no storage // attempts to store the value "0" at any key. Putting this value (and therefore requiring // that the value be committed into the storage trie after execution) would incorrectly // modify the storage root. if (_getContractStorage(_contract, _key) == _value) { return; } _checkContractStorageChange(_contract, _key); ovmStateManager.putContractStorage(_contract, _key, _value); } /** * Validation whenever a contract needs to be loaded. Checks that the account exists, charges * nuisance gas if the account hasn't been loaded before. * @param _address Address of the account to load. */ function _checkAccountLoad( address _address ) internal { // See `_checkContractStorageLoad` for more information. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // See `_checkContractStorageLoad` for more information. if (ovmStateManager.hasAccount(_address) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the account has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that an account is loaded. ( bool _wasAccountAlreadyLoaded ) = ovmStateManager.testAndSetAccountLoaded(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyLoaded == false) { _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a contract needs to be changed. Checks that the account exists, charges * nuisance gas if the account hasn't been changed before. * @param _address Address of the account to change. */ function _checkAccountChange( address _address ) internal { // Start by checking for a load as we only want to charge nuisance gas proportional to // contract size once. _checkAccountLoad(_address); // Check whether the account has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that an account is changed. ( bool _wasAccountAlreadyChanged ) = ovmStateManager.testAndSetAccountChanged(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyChanged == false) { ovmStateManager.incrementTotalUncommittedAccounts(); _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a slot needs to be loaded. Checks that the account exists, charges * nuisance gas if the slot hasn't been loaded before. * @param _contract Address of the account to load from. * @param _key 32 byte key to load. */ function _checkContractStorageLoad( address _contract, bytes32 _key ) internal { // Another case of hidden complexity. If we didn't enforce this requirement, then a // contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail // on L1 but not on L2. A contract could use this behavior to prevent the // OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS // allows us to also charge for the full message nuisance gas, because you deserve that for // trying to break the contract in this way. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // We need to make sure that the transaction isn't trying to access storage that hasn't // been provided to the OVM_StateManager. We'll immediately abort if this is the case. // We know that we have enough gas to do this check because of the above test. if (ovmStateManager.hasContractStorage(_contract, _key) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the slot has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that a slot is loaded. ( bool _wasContractStorageAlreadyLoaded ) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key); // If we hadn't already loaded the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyLoaded == false) { _useNuisanceGas(NUISANCE_GAS_SLOAD); } } /** * Validation whenever a slot needs to be changed. Checks that the account exists, charges * nuisance gas if the slot hasn't been changed before. * @param _contract Address of the account to change. * @param _key 32 byte key to change. */ function _checkContractStorageChange( address _contract, bytes32 _key ) internal { // Start by checking for load to make sure we have the storage slot and that we charge the // "nuisance gas" necessary to prove the storage slot state. _checkContractStorageLoad(_contract, _key); // Check whether the slot has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that a slot is changed. ( bool _wasContractStorageAlreadyChanged ) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key); // If we hadn't already changed the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyChanged == false) { // Changing a storage slot means that we're also going to have to change the // corresponding account, so do an account change check. _checkAccountChange(_contract); ovmStateManager.incrementTotalUncommittedContractStorage(); _useNuisanceGas(NUISANCE_GAS_SSTORE); } } /************************************ * Internal Functions: Revert Logic * ************************************/ /** * Simple encoding for revert data. * @param _flag Flag to revert with. * @param _data Additional user-provided revert data. * @return _revertdata Encoded revert data. */ function _encodeRevertData( RevertFlag _flag, bytes memory _data ) internal view returns ( bytes memory _revertdata ) { // Out of gas and create exceptions will fundamentally return no data, so simulating it // shouldn't either. if ( _flag == RevertFlag.OUT_OF_GAS ) { return bytes(""); } // INVALID_STATE_ACCESS doesn't need to return any data other than the flag. if (_flag == RevertFlag.INVALID_STATE_ACCESS) { return abi.encode( _flag, 0, 0, bytes("") ); } // Just ABI encode the rest of the parameters. return abi.encode( _flag, messageRecord.nuisanceGasLeft, transactionRecord.ovmGasRefund, _data ); } /** * Simple decoding for revert data. * @param _revertdata Revert data to decode. * @return _flag Flag used to revert. * @return _nuisanceGasLeft Amount of nuisance gas unused by the message. * @return _ovmGasRefund Amount of gas refunded during the message. * @return _data Additional user-provided revert data. */ function _decodeRevertData( bytes memory _revertdata ) internal pure returns ( RevertFlag _flag, uint256 _nuisanceGasLeft, uint256 _ovmGasRefund, bytes memory _data ) { // A length of zero means the call ran out of gas, just return empty data. if (_revertdata.length == 0) { return ( RevertFlag.OUT_OF_GAS, 0, 0, bytes("") ); } // ABI decode the incoming data. return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes)); } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. * @param _data Additional user-provided data. */ function _revertWithFlag( RevertFlag _flag, bytes memory _data ) internal view { bytes memory revertdata = _encodeRevertData( _flag, _data ); assembly { revert(add(revertdata, 0x20), mload(revertdata)) } } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. */ function _revertWithFlag( RevertFlag _flag ) internal { _revertWithFlag(_flag, bytes("")); } /****************************************** * Internal Functions: Nuisance Gas Logic * ******************************************/ /** * Computes the nuisance gas limit from the gas limit. * @dev This function is currently using a naive implementation whereby the nuisance gas limit * is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that * this implementation is perfectly fine, but we may change this formula later. * @param _gasLimit Gas limit to compute from. * @return _nuisanceGasLimit Computed nuisance gas limit. */ function _getNuisanceGasLimit( uint256 _gasLimit ) internal view returns ( uint256 _nuisanceGasLimit ) { return _gasLimit < gasleft() ? _gasLimit : gasleft(); } /** * Uses a certain amount of nuisance gas. * @param _amount Amount of nuisance gas to use. */ function _useNuisanceGas( uint256 _amount ) internal { // Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas // refund to be given at the end of the transaction. if (messageRecord.nuisanceGasLeft < _amount) { _revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS); } messageRecord.nuisanceGasLeft -= _amount; } /************************************ * Internal Functions: Gas Metering * ************************************/ /** * Checks whether a transaction needs to start a new epoch and does so if necessary. * @param _timestamp Transaction timestamp. */ function _checkNeedsNewEpoch( uint256 _timestamp ) internal { if ( _timestamp >= ( _getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP) + gasMeterConfig.secondsPerEpoch ) ) { _putGasMetadata( GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP, _timestamp ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS ) ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS ) ); } } /** * Validates the input values of a transaction. * @return _valid Whether or not the transaction data is valid. */ function _isValidInput( Lib_OVMCodec.Transaction memory _transaction ) view internal returns ( bool ) { // Prevent reentrancy to run(): // This check prevents calling run with the default ovmNumber. // Combined with the first check in run(): // if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // It should be impossible to re-enter since run() returns before any other call frames are // created. Since this value is already being written to storage, we save much gas compared // to using the standard nonReentrant pattern. if (_transaction.blockNumber == DEFAULT_UINT256) { return false; } if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) { return false; } return true; } /** * Validates the gas limit for a given transaction. * @param _gasLimit Gas limit provided by the transaction. * param _queueOrigin Queue from which the transaction originated. * @return _valid Whether or not the gas limit is valid. */ function _isValidGasLimit( uint256 _gasLimit, Lib_OVMCodec.QueueOrigin // _queueOrigin ) view internal returns ( bool _valid ) { // Always have to be below the maximum gas limit. if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) { return false; } // Always have to be above the minimum gas limit. if (_gasLimit < gasMeterConfig.minTransactionGasLimit) { return false; } // TEMPORARY: Gas metering is disabled for minnet. return true; // GasMetadataKey cumulativeGasKey; // GasMetadataKey prevEpochGasKey; // if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS; // } else { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS; // } // return ( // ( // _getGasMetadata(cumulativeGasKey) // - _getGasMetadata(prevEpochGasKey) // + _gasLimit // ) < gasMeterConfig.maxGasPerQueuePerEpoch // ); } /** * Updates the cumulative gas after a transaction. * @param _gasUsed Gas used by the transaction. * @param _queueOrigin Queue from which the transaction originated. */ function _updateCumulativeGas( uint256 _gasUsed, Lib_OVMCodec.QueueOrigin _queueOrigin ) internal { GasMetadataKey cumulativeGasKey; if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; } else { cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; } _putGasMetadata( cumulativeGasKey, ( _getGasMetadata(cumulativeGasKey) + gasMeterConfig.minTransactionGasLimit + _gasUsed - transactionRecord.ovmGasRefund ) ); } /** * Retrieves the value of a gas metadata key. * @param _key Gas metadata key to retrieve. * @return _value Value stored at the given key. */ function _getGasMetadata( GasMetadataKey _key ) internal returns ( uint256 _value ) { return uint256(_getContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)) )); } /** * Sets the value of a gas metadata key. * @param _key Gas metadata key to set. * @param _value Value to store at the given key. */ function _putGasMetadata( GasMetadataKey _key, uint256 _value ) internal { _putContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)), bytes32(uint256(_value)) ); } /***************************************** * Internal Functions: Execution Context * *****************************************/ /** * Swaps over to a new message context. * @param _prevMessageContext Context we're switching from. * @param _nextMessageContext Context we're switching to. */ function _switchMessageContext( MessageContext memory _prevMessageContext, MessageContext memory _nextMessageContext ) internal { // These conditionals allow us to avoid unneccessary SSTOREs. However, they do mean that // the current storage value for the messageContext MUST equal the _prevMessageContext // argument, or an SSTORE might be erroneously skipped. if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) { messageContext.ovmCALLER = _nextMessageContext.ovmCALLER; } if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) { messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS; } if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) { messageContext.isStatic = _nextMessageContext.isStatic; } if (_prevMessageContext.ovmCALLVALUE != _nextMessageContext.ovmCALLVALUE) { messageContext.ovmCALLVALUE = _nextMessageContext.ovmCALLVALUE; } } /** * Initializes the execution context. * @param _transaction OVM transaction being executed. */ function _initContext( Lib_OVMCodec.Transaction memory _transaction ) internal { transactionContext.ovmTIMESTAMP = _transaction.timestamp; transactionContext.ovmNUMBER = _transaction.blockNumber; transactionContext.ovmTXGASLIMIT = _transaction.gasLimit; transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin; transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin; transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch; messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit); } /** * Resets the transaction and message context. */ function _resetContext() internal { transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS; transactionContext.ovmTIMESTAMP = DEFAULT_UINT256; transactionContext.ovmNUMBER = DEFAULT_UINT256; transactionContext.ovmGASLIMIT = DEFAULT_UINT256; transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256; transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE; transactionRecord.ovmGasRefund = DEFAULT_UINT256; messageContext.ovmCALLER = DEFAULT_ADDRESS; messageContext.ovmADDRESS = DEFAULT_ADDRESS; messageContext.isStatic = false; messageRecord.nuisanceGasLeft = DEFAULT_UINT256; // Reset the ovmStateManager. ovmStateManager = iOVM_StateManager(address(0)); } /****************************************** * Internal Functions: Message Typechecks * ******************************************/ /** * Returns whether or not the given message type is a CREATE-type. * @param _messageType the message type in question. */ function _isCreateType( MessageType _messageType ) internal pure returns( bool ) { return ( _messageType == MessageType.ovmCREATE || _messageType == MessageType.ovmCREATE2 ); } /** * Returns whether or not the given message type (potentially) requires the transfer of ETH * value along with the message. * @param _messageType the message type in question. */ function _isValueType( MessageType _messageType ) internal pure returns( bool ) { // ovmSTATICCALL and ovmDELEGATECALL types do not accept or transfer value. return ( _messageType == MessageType.ovmCALL || _messageType == MessageType.ovmCREATE || _messageType == MessageType.ovmCREATE2 ); } /***************************** * L2-only Helper Functions * *****************************/ /** * Unreachable helper function for simulating eth_calls with an OVM message context. * This function will throw an exception in all cases other than when used as a custom * entrypoint in L2 Geth to simulate eth_call. * @param _transaction the message transaction to simulate. * @param _from the OVM account the simulated call should be from. * @param _value the amount of ETH value to send. * @param _ovmStateManager the address of the OVM_StateManager precompile in the L2 state. */ function simulateMessage( Lib_OVMCodec.Transaction memory _transaction, address _from, uint256 _value, iOVM_StateManager _ovmStateManager ) external returns ( bytes memory ) { // Prevent this call from having any effect unless in a custom-set VM frame require(msg.sender == address(0)); // Initialize the EM's internal state, ignoring nuisance gas. ovmStateManager = _ovmStateManager; _initContext(_transaction); messageRecord.nuisanceGasLeft = uint(-1); // Set the ovmADDRESS to the _from so that the subsequent call frame "comes from" them. messageContext.ovmADDRESS = _from; // Execute the desired message. bool isCreate = _transaction.entrypoint == address(0); if (isCreate) { (address created, bytes memory revertData) = ovmCREATE(_transaction.data); if (created == address(0)) { return abi.encode(false, revertData); } else { // The eth_call RPC endpoint for to = undefined will return the deployed bytecode // in the success case, differing from standard create messages. return abi.encode(true, Lib_EthUtils.getCode(created)); } } else { (bool success, bytes memory returndata) = ovmCALL( _transaction.gasLimit, _transaction.entrypoint, _value, _transaction.data ); return abi.encode(success, returndata); } } } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_SafetyChecker */ interface iOVM_SafetyChecker { /******************** * Public Functions * ********************/ function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_DeployerWhitelist } from "../../iOVM/predeploys/iOVM_DeployerWhitelist.sol"; /** * @title OVM_DeployerWhitelist * @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the * initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts * which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an * ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_DeployerWhitelist is iOVM_DeployerWhitelist { /********************** * Contract Constants * **********************/ bool public initialized; bool public allowArbitraryDeployment; address override public owner; mapping (address => bool) public whitelist; /********************** * Function Modifiers * **********************/ /** * Blocks functions to anyone except the contract owner. */ modifier onlyOwner() { require( msg.sender == owner, "Function can only be called by the owner of this contract." ); _; } /******************** * Public Functions * ********************/ /** * Initializes the whitelist. * @param _owner Address of the owner for this contract. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function initialize( address _owner, bool _allowArbitraryDeployment ) override external { if (initialized == true) { return; } initialized = true; allowArbitraryDeployment = _allowArbitraryDeployment; owner = _owner; } /** * Adds or removes an address from the deployment whitelist. * @param _deployer Address to update permissions for. * @param _isWhitelisted Whether or not the address is whitelisted. */ function setWhitelistedDeployer( address _deployer, bool _isWhitelisted ) override external onlyOwner { whitelist[_deployer] = _isWhitelisted; } /** * Updates the owner of this contract. * @param _owner Address of the new owner. */ function setOwner( address _owner ) override public onlyOwner { owner = _owner; } /** * Updates the arbitrary deployment flag. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function setAllowArbitraryDeployment( bool _allowArbitraryDeployment ) override public onlyOwner { allowArbitraryDeployment = _allowArbitraryDeployment; } /** * Permanently enables arbitrary contract deployment and deletes the owner. */ function enableArbitraryContractDeployment() override external onlyOwner { setAllowArbitraryDeployment(true); setOwner(address(0)); } /** * Checks whether an address is allowed to deploy contracts. * @param _deployer Address to check. * @return _allowed Whether or not the address can deploy contracts. */ function isDeployerAllowed( address _deployer ) override external returns ( bool ) { return ( initialized == false || allowArbitraryDeployment == true || whitelist[_deployer] ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_DeployerWhitelist */ interface iOVM_DeployerWhitelist { /******************** * Public Functions * ********************/ function initialize(address _owner, bool _allowArbitraryDeployment) external; function owner() external returns (address _owner); function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external; function setOwner(address _newOwner) external; function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external; function enableArbitraryContractDeployment() external; function isDeployerAllowed(address _deployer) external returns (bool _allowed); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /** * @title OVM_SafetyChecker * @dev The Safety Checker verifies that contracts deployed on L2 do not contain any * "unsafe" operations. An operation is considered unsafe if it would access state variables which * are specific to the environment (ie. L1 or L2) in which it is executed, as this could be used * to "escape the sandbox" of the OVM, resulting in non-deterministic fraud proofs. * That is, an attacker would be able to "prove fraud" on an honestly applied transaction. * Note that a "safe" contract requires opcodes to appear in a particular pattern; * omission of "unsafe" opcodes is necessary, but not sufficient. * * Compiler used: solc * Runtime target: EVM */ contract OVM_SafetyChecker is iOVM_SafetyChecker { /******************** * Public Functions * ********************/ /** * Returns whether or not all of the provided bytecode is safe. * @param _bytecode The bytecode to safety check. * @return `true` if the bytecode is safe, `false` otherwise. */ function isBytecodeSafe( bytes memory _bytecode ) override external pure returns ( bool ) { // autogenerated by gen_safety_checker_constants.py // number of bytes to skip for each opcode uint256[8] memory opcodeSkippableBytes = [ uint256(0x0001010101010101010101010000000001010101010101010101010101010000), uint256(0x0100000000000000000000000000000000000000010101010101000000010100), uint256(0x0000000000000000000000000000000001010101000000010101010100000000), uint256(0x0203040500000000000000000000000000000000000000000000000000000000), uint256(0x0101010101010101010101010101010101010101010101010101010101010101), uint256(0x0101010101000000000000000000000000000000000000000000000000000000), uint256(0x0000000000000000000000000000000000000000000000000000000000000000), uint256(0x0000000000000000000000000000000000000000000000000000000000000000) ]; // Mask to gate opcode specific cases // solhint-disable-next-line max-line-length uint256 opcodeGateMask = ~uint256(0xffffffffffffffffffffffe000000000fffffffff070ffff9c0ffffec000f001); // Halting opcodes // solhint-disable-next-line max-line-length uint256 opcodeHaltingMask = ~uint256(0x4008000000000000000000000000000000000000004000000000000000000001); // PUSH opcodes uint256 opcodePushMask = ~uint256(0xffffffff000000000000000000000000); uint256 codeLength; uint256 _pc; assembly { _pc := add(_bytecode, 0x20) } codeLength = _pc + _bytecode.length; do { // current opcode: 0x00...0xff uint256 opNum; /* solhint-disable max-line-length */ // inline assembly removes the extra add + bounds check assembly { let word := mload(_pc) //load the next 32 bytes at pc into word // Look up number of bytes to skip from opcodeSkippableBytes and then update indexInWord // E.g. the 02030405 in opcodeSkippableBytes is the number of bytes to skip for PUSH1->4 // We repeat this 6 times, thus we can only skip bytes for up to PUSH4 ((1+4) * 6 = 30 < 32). // If we see an opcode that is listed as 0 skippable bytes e.g. PUSH5, // then we will get stuck on that indexInWord and then opNum will be set to the PUSH5 opcode. let indexInWord := byte(0, mload(add(opcodeSkippableBytes, byte(0, word)))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) _pc := add(_pc, indexInWord) opNum := byte(indexInWord, word) } /* solhint-enable max-line-length */ // + push opcodes // + stop opcodes [STOP(0x00),JUMP(0x56),RETURN(0xf3),INVALID(0xfe)] // + caller opcode CALLER(0x33) // + blacklisted opcodes uint256 opBit = 1 << opNum; if (opBit & opcodeGateMask == 0) { if (opBit & opcodePushMask == 0) { // all pushes are valid opcodes // subsequent bytes are not opcodes. Skip them. _pc += (opNum - 0x5e); // PUSH1 is 0x60, so opNum-0x5f = PUSHed bytes and we // +1 to skip the _pc++; line below in order to save gas ((-0x5f + 1) = -0x5e) continue; } else if (opBit & opcodeHaltingMask == 0) { // STOP or JUMP or RETURN or INVALID (Note: REVERT is blacklisted, so not // included here) // We are now inside unreachable code until we hit a JUMPDEST! do { _pc++; assembly { opNum := byte(0, mload(_pc)) } // encountered a JUMPDEST if (opNum == 0x5b) break; // skip PUSHed bytes // opNum-0x5f = PUSHed bytes (PUSH1 is 0x60) if ((1 << opNum) & opcodePushMask == 0) _pc += (opNum - 0x5f); } while (_pc < codeLength); // opNum is 0x5b, so we don't continue here since the pc++ is fine } else if (opNum == 0x33) { // Caller opcode uint256 firstOps; // next 32 bytes of bytecode uint256 secondOps; // following 32 bytes of bytecode assembly { firstOps := mload(_pc) // 37 bytes total, 5 left over --> 32 - 5 bytes = 27 bytes = 216 bits secondOps := shr(216, mload(add(_pc, 0x20))) } // Call identity precompile // CALLER POP PUSH1 0x00 PUSH1 0x04 GAS CALL // 32 - 8 bytes = 24 bytes = 192 if ((firstOps >> 192) == 0x3350600060045af1) { _pc += 8; // Call EM and abort execution if instructed // CALLER PUSH1 0x00 SWAP1 GAS CALL PC PUSH1 0x0E ADD JUMPI RETURNDATASIZE // PUSH1 0x00 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x00 REVERT JUMPDEST // RETURNDATASIZE PUSH1 0x01 EQ ISZERO PC PUSH1 0x0a ADD JUMPI PUSH1 0x01 PUSH1 // 0x00 RETURN JUMPDEST // solhint-disable-next-line max-line-length } else if (firstOps == 0x336000905af158600e01573d6000803e3d6000fd5b3d6001141558600a015760 && secondOps == 0x016000f35b) { _pc += 37; } else { return false; } continue; } else { // encountered a non-whitelisted opcode! return false; } } _pc++; } while (_pc < codeLength); return true; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol"; /* Contract Imports */ import { OVM_StateManager } from "./OVM_StateManager.sol"; /** * @title OVM_StateManagerFactory * @dev The State Manager Factory is called by a State Transitioner's init code, to create a new * State Manager for use in the Fraud Verification process. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateManagerFactory is iOVM_StateManagerFactory { /******************** * Public Functions * ********************/ /** * Creates a new OVM_StateManager * @param _owner Owner of the created contract. * @return New OVM_StateManager instance. */ function create( address _owner ) override public returns ( iOVM_StateManager ) { return new OVM_StateManager(_owner); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; /** * @title OVM_StateManager * @dev The State Manager contract holds all storage values for contracts in the OVM. It can only be * written to by the Execution Manager and State Transitioner. It runs on L1 during the setup and * execution of a fraud proof. * The same logic runs on L2, but has been implemented as a precompile in the L2 go-ethereum client * (see https://github.com/ethereum-optimism/go-ethereum/blob/master/core/vm/ovm_state_manager.go). * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateManager is iOVM_StateManager { /************* * Constants * *************/ bytes32 constant internal EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421; bytes32 constant internal EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 constant internal STORAGE_XOR_VALUE = 0xFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEF; /************* * Variables * *************/ address override public owner; address override public ovmExecutionManager; mapping (address => Lib_OVMCodec.Account) internal accounts; mapping (address => mapping (bytes32 => bytes32)) internal contractStorage; mapping (address => mapping (bytes32 => bool)) internal verifiedContractStorage; mapping (bytes32 => ItemState) internal itemStates; uint256 internal totalUncommittedAccounts; uint256 internal totalUncommittedContractStorage; /*************** * Constructor * ***************/ /** * @param _owner Address of the owner of this contract. */ constructor( address _owner ) { owner = _owner; } /********************** * Function Modifiers * **********************/ /** * Simple authentication, this contract should only be accessible to the owner * (which is expected to be the State Transitioner during `PRE_EXECUTION` * or the OVM_ExecutionManager during transaction execution. */ modifier authenticated() { // owner is the State Transitioner require( msg.sender == owner || msg.sender == ovmExecutionManager, "Function can only be called by authenticated addresses" ); _; } /******************** * Public Functions * ********************/ /** * Checks whether a given address is allowed to modify this contract. * @param _address Address to check. * @return Whether or not the address can modify this contract. */ function isAuthenticated( address _address ) override public view returns ( bool ) { return (_address == owner || _address == ovmExecutionManager); } /** * Sets the address of the OVM_ExecutionManager. * @param _ovmExecutionManager Address of the OVM_ExecutionManager. */ function setExecutionManager( address _ovmExecutionManager ) override public authenticated { ovmExecutionManager = _ovmExecutionManager; } /** * Inserts an account into the state. * @param _address Address of the account to insert. * @param _account Account to insert for the given address. */ function putAccount( address _address, Lib_OVMCodec.Account memory _account ) override public authenticated { accounts[_address] = _account; } /** * Marks an account as empty. * @param _address Address of the account to mark. */ function putEmptyAccount( address _address ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT; account.codeHash = EMPTY_ACCOUNT_CODE_HASH; } /** * Retrieves an account from the state. * @param _address Address of the account to retrieve. * @return Account for the given address. */ function getAccount( address _address ) override public view returns ( Lib_OVMCodec.Account memory ) { return accounts[_address]; } /** * Checks whether the state has a given account. * @param _address Address of the account to check. * @return Whether or not the state has the account. */ function hasAccount( address _address ) override public view returns ( bool ) { return accounts[_address].codeHash != bytes32(0); } /** * Checks whether the state has a given known empty account. * @param _address Address of the account to check. * @return Whether or not the state has the empty account. */ function hasEmptyAccount( address _address ) override public view returns ( bool ) { return ( accounts[_address].codeHash == EMPTY_ACCOUNT_CODE_HASH && accounts[_address].nonce == 0 ); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function setAccountNonce( address _address, uint256 _nonce ) override public authenticated { accounts[_address].nonce = _nonce; } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return Nonce of the account. */ function getAccountNonce( address _address ) override public view returns ( uint256 ) { return accounts[_address].nonce; } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return Corresponding Ethereum address. */ function getAccountEthAddress( address _address ) override public view returns ( address ) { return accounts[_address].ethAddress; } /** * Retrieves the storage root of an account. * @param _address Address of the account to access. * @return Corresponding storage root. */ function getAccountStorageRoot( address _address ) override public view returns ( bytes32 ) { return accounts[_address].storageRoot; } /** * Initializes a pending account (during CREATE or CREATE2) with the default values. * @param _address Address of the account to initialize. */ function initPendingAccount( address _address ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.nonce = 1; account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT; account.codeHash = EMPTY_ACCOUNT_CODE_HASH; account.isFresh = true; } /** * Finalizes the creation of a pending account (during CREATE or CREATE2). * @param _address Address of the account to finalize. * @param _ethAddress Address of the account's associated contract on Ethereum. * @param _codeHash Hash of the account's code. */ function commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.ethAddress = _ethAddress; account.codeHash = _codeHash; } /** * Checks whether an account has already been retrieved, and marks it as retrieved if not. * @param _address Address of the account to check. * @return Whether or not the account was already loaded. */ function testAndSetAccountLoaded( address _address ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_address), ItemState.ITEM_LOADED ); } /** * Checks whether an account has already been modified, and marks it as modified if not. * @param _address Address of the account to check. * @return Whether or not the account was already modified. */ function testAndSetAccountChanged( address _address ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_address), ItemState.ITEM_CHANGED ); } /** * Attempts to mark an account as committed. * @param _address Address of the account to commit. * @return Whether or not the account was committed. */ function commitAccount( address _address ) override public authenticated returns ( bool ) { bytes32 item = _getItemHash(_address); if (itemStates[item] != ItemState.ITEM_CHANGED) { return false; } itemStates[item] = ItemState.ITEM_COMMITTED; totalUncommittedAccounts -= 1; return true; } /** * Increments the total number of uncommitted accounts. */ function incrementTotalUncommittedAccounts() override public authenticated { totalUncommittedAccounts += 1; } /** * Gets the total number of uncommitted accounts. * @return Total uncommitted accounts. */ function getTotalUncommittedAccounts() override public view returns ( uint256 ) { return totalUncommittedAccounts; } /** * Checks whether a given account was changed during execution. * @param _address Address to check. * @return Whether or not the account was changed. */ function wasAccountChanged( address _address ) override public view returns ( bool ) { bytes32 item = _getItemHash(_address); return itemStates[item] >= ItemState.ITEM_CHANGED; } /** * Checks whether a given account was committed after execution. * @param _address Address to check. * @return Whether or not the account was committed. */ function wasAccountCommitted( address _address ) override public view returns ( bool ) { bytes32 item = _getItemHash(_address); return itemStates[item] >= ItemState.ITEM_COMMITTED; } /************************************ * Public Functions: Storage Access * ************************************/ /** * Changes a contract storage slot value. * @param _contract Address of the contract to modify. * @param _key 32 byte storage slot key. * @param _value 32 byte storage slot value. */ function putContractStorage( address _contract, bytes32 _key, bytes32 _value ) override public authenticated { // A hilarious optimization. `SSTORE`ing a value of `bytes32(0)` is common enough that it's // worth populating this with a non-zero value in advance (during the fraud proof // initialization phase) to cut the execution-time cost down to 5000 gas. contractStorage[_contract][_key] = _value ^ STORAGE_XOR_VALUE; // Only used when initially populating the contract storage. OVM_ExecutionManager will // perform a `hasContractStorage` INVALID_STATE_ACCESS check before putting any contract // storage because writing to zero when the actual value is nonzero causes a gas // discrepancy. Could be moved into a new `putVerifiedContractStorage` function, or // something along those lines. if (verifiedContractStorage[_contract][_key] == false) { verifiedContractStorage[_contract][_key] = true; } } /** * Retrieves a contract storage slot value. * @param _contract Address of the contract to access. * @param _key 32 byte storage slot key. * @return 32 byte storage slot value. */ function getContractStorage( address _contract, bytes32 _key ) override public view returns ( bytes32 ) { // Storage XOR system doesn't work for newly created contracts that haven't set this // storage slot value yet. if ( verifiedContractStorage[_contract][_key] == false && accounts[_contract].isFresh ) { return bytes32(0); } // See `putContractStorage` for more information about the XOR here. return contractStorage[_contract][_key] ^ STORAGE_XOR_VALUE; } /** * Checks whether a contract storage slot exists in the state. * @param _contract Address of the contract to access. * @param _key 32 byte storage slot key. * @return Whether or not the key was set in the state. */ function hasContractStorage( address _contract, bytes32 _key ) override public view returns ( bool ) { return verifiedContractStorage[_contract][_key] || accounts[_contract].isFresh; } /** * Checks whether a storage slot has already been retrieved, and marks it as retrieved if not. * @param _contract Address of the contract to check. * @param _key 32 byte storage slot key. * @return Whether or not the slot was already loaded. */ function testAndSetContractStorageLoaded( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_contract, _key), ItemState.ITEM_LOADED ); } /** * Checks whether a storage slot has already been modified, and marks it as modified if not. * @param _contract Address of the contract to check. * @param _key 32 byte storage slot key. * @return Whether or not the slot was already modified. */ function testAndSetContractStorageChanged( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_contract, _key), ItemState.ITEM_CHANGED ); } /** * Attempts to mark a storage slot as committed. * @param _contract Address of the account to commit. * @param _key 32 byte slot key to commit. * @return Whether or not the slot was committed. */ function commitContractStorage( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); if (itemStates[item] != ItemState.ITEM_CHANGED) { return false; } itemStates[item] = ItemState.ITEM_COMMITTED; totalUncommittedContractStorage -= 1; return true; } /** * Increments the total number of uncommitted storage slots. */ function incrementTotalUncommittedContractStorage() override public authenticated { totalUncommittedContractStorage += 1; } /** * Gets the total number of uncommitted storage slots. * @return Total uncommitted storage slots. */ function getTotalUncommittedContractStorage() override public view returns ( uint256 ) { return totalUncommittedContractStorage; } /** * Checks whether a given storage slot was changed during execution. * @param _contract Address to check. * @param _key Key of the storage slot to check. * @return Whether or not the storage slot was changed. */ function wasContractStorageChanged( address _contract, bytes32 _key ) override public view returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); return itemStates[item] >= ItemState.ITEM_CHANGED; } /** * Checks whether a given storage slot was committed after execution. * @param _contract Address to check. * @param _key Key of the storage slot to check. * @return Whether or not the storage slot was committed. */ function wasContractStorageCommitted( address _contract, bytes32 _key ) override public view returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); return itemStates[item] >= ItemState.ITEM_COMMITTED; } /********************** * Internal Functions * **********************/ /** * Generates a unique hash for an address. * @param _address Address to generate a hash for. * @return Unique hash for the given address. */ function _getItemHash( address _address ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_address)); } /** * Generates a unique hash for an address/key pair. * @param _contract Address to generate a hash for. * @param _key Key to generate a hash for. * @return Unique hash for the given pair. */ function _getItemHash( address _contract, bytes32 _key ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked( _contract, _key )); } /** * Checks whether an item is in a particular state (ITEM_LOADED or ITEM_CHANGED) and sets the * item to the provided state if not. * @param _item 32 byte item ID to check. * @param _minItemState Minimum state that must be satisfied by the item. * @return Whether or not the item was already in the state. */ function _testAndSetItemState( bytes32 _item, ItemState _minItemState ) internal returns ( bool ) { bool wasItemState = itemStates[_item] >= _minItemState; if (wasItemState == false) { itemStates[_item] = _minItemState; } return wasItemState; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../optimistic-ethereum/libraries/codec/Lib_OVMCodec.sol"; /** * @title TestLib_OVMCodec */ contract TestLib_OVMCodec { function encodeTransaction( Lib_OVMCodec.Transaction memory _transaction ) public pure returns ( bytes memory _encoded ) { return Lib_OVMCodec.encodeTransaction(_transaction); } function hashTransaction( Lib_OVMCodec.Transaction memory _transaction ) public pure returns ( bytes32 _hash ) { return Lib_OVMCodec.hashTransaction(_transaction); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressManager } from "../../../libraries/resolver/Lib_AddressManager.sol"; import { Lib_SecureMerkleTrie } from "../../../libraries/trie/Lib_SecureMerkleTrie.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol"; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_CanonicalTransactionChain } from "../../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_StateCommitmentChain } from "../../../iOVM/chain/iOVM_StateCommitmentChain.sol"; /* External Imports */ import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; /** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /************* * Constants * *************/ // The default x-domain message sender being set to a non-zero value makes // deployment a bit more expensive, but in exchange the refund on every call to // `relayMessage` by the L1 and L2 messengers will be higher. address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD; /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; mapping (bytes32 => bool) public relayedMessages; mapping (bytes32 => bool) public successfulMessages; address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } function xDomainMessageSender() public override view returns ( address ) { require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set"); return xDomainMsgSender; } /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) override public { address ovmCanonicalTransactionChain = resolve("OVM_CanonicalTransactionChain"); // Use the CTC queue length as nonce uint40 nonce = iOVM_CanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength(); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, msg.sender, _message, nonce ); address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger"); _sendXDomainMessage( ovmCanonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit ); emit SentMessage(xDomainCalldata); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); require( _target != resolve("OVM_CanonicalTransactionChain"), "Cannot send L2->L1 messages to L1 system contracts." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _queueIndex, uint32 _gasLimit ) override public { // Verify that the message is in the queue: address canonicalTransactionChain = resolve("OVM_CanonicalTransactionChain"); Lib_OVMCodec.QueueElement memory element = iOVM_CanonicalTransactionChain(canonicalTransactionChain).getQueueElement(_queueIndex); address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger"); // Compute the transactionHash bytes32 transactionHash = keccak256( abi.encode( address(this), l2CrossDomainMessenger, _gasLimit, _message ) ); require( transactionHash == element.transactionHash, "Provided message has not been enqueued." ); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _queueIndex ); _sendXDomainMessage( canonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit ); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _canonicalTransactionChain Address of the OVM_CanonicalTransactionChain instance. * @param _l2CrossDomainMessenger Address of the OVM_L2CrossDomainMessenger instance. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( address _canonicalTransactionChain, address _l2CrossDomainMessenger, bytes memory _message, uint256 _gasLimit ) internal { iOVM_CanonicalTransactionChain(_canonicalTransactionChain).enqueue( _l2CrossDomainMessenger, _gasLimit, _message ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; /** * @title Lib_CrossDomainUtils */ library Lib_CrossDomainUtils { /** * Generates the correct cross domain calldata for a message. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @return ABI encoded cross domain calldata. */ function encodeXDomainCalldata( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "relayMessage(address,address,bytes,uint256)", _target, _sender, _message, _messageNonce ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol"; /** * @title iOVM_L1CrossDomainMessenger */ interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger { /******************* * Data Structures * *******************/ struct L2MessageInclusionProof { bytes32 stateRoot; Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader; Lib_OVMCodec.ChainInclusionProof stateRootProof; bytes stateTrieWitness; bytes storageTrieWitness; } /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @param _proof Inclusion proof for the given message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) external; /** * Replays a cross domain message to the target messenger. * @param _target Target contract address. * @param _sender Original sender address. * @param _message Message to send to the target. * @param _queueIndex CTC Queue index for the message to replay. * @param _gasLimit Gas limit for the provided message. */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _queueIndex, uint32 _gasLimit ) external; } // 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.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 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.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 // 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 // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_L1MultiMessageRelayer } from "../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol"; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title OVM_L1MultiMessageRelayer * @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the * relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain * Message Sender. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver { /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /********************** * Function Modifiers * **********************/ modifier onlyBatchRelayer() { require( msg.sender == resolve("OVM_L2BatchMessageRelayer"), // solhint-disable-next-line max-line-length "OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer" ); _; } /******************** * Public Functions * ********************/ /** * @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying * @param _messages An array of L2 to L1 messages */ function batchRelayMessages( L2ToL1Message[] calldata _messages ) override external onlyBatchRelayer { iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger( resolve("Proxy__OVM_L1CrossDomainMessenger") ); for (uint256 i = 0; i < _messages.length; i++) { L2ToL1Message memory message = _messages[i]; messenger.relayMessage( message.target, message.sender, message.message, message.messageNonce, message.proof ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; interface iOVM_L1MultiMessageRelayer { struct L2ToL1Message { address target; address sender; bytes message; uint256 messageNonce; iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof; } function batchRelayMessages(L2ToL1Message[] calldata _messages) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol"; /* Interface Imports */ import { iOVM_L2CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L2CrossDomainMessenger.sol"; import { iOVM_L1MessageSender } from "../../../iOVM/predeploys/iOVM_L1MessageSender.sol"; import { iOVM_L2ToL1MessagePasser } from "../../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol"; /* External Imports */ import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /* External Imports */ import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /** * @title OVM_L2CrossDomainMessenger * @dev The L2 Cross Domain Messenger contract sends messages from L2 to L1, and is the entry point * for L2 messages sent via the L1 Cross Domain Messenger. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2CrossDomainMessenger is iOVM_L2CrossDomainMessenger, Lib_AddressResolver, ReentrancyGuard { /************* * Constants * *************/ // The default x-domain message sender being set to a non-zero value makes // deployment a bit more expensive, but in exchange the refund on every call to // `relayMessage` by the L1 and L2 messengers will be higher. address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD; /************* * Variables * *************/ mapping (bytes32 => bool) public relayedMessages; mapping (bytes32 => bool) public successfulMessages; mapping (bytes32 => bool) public sentMessages; uint256 public messageNonce; address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor(address _libAddressManager) Lib_AddressResolver(_libAddressManager) ReentrancyGuard() {} /******************** * Public Functions * ********************/ function xDomainMessageSender() public override view returns ( address ) { require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set"); return xDomainMsgSender; } /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, msg.sender, _message, messageNonce ); messageNonce += 1; sentMessages[keccak256(xDomainCalldata)] = true; _sendXDomainMessage(xDomainCalldata, _gasLimit); emit SentMessage(xDomainCalldata); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L2CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) override nonReentrant public { require( _verifyXDomainMessage() == true, "Provided message could not be verified." ); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _messageNonce ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); // Prevent calls to OVM_L2ToL1MessagePasser, which would enable // an attacker to maliciously craft the _message to spoof // a call from any L2 account. if(_target == resolve("OVM_L2ToL1MessagePasser")){ // Write to the successfulMessages mapping and return immediately. successfulMessages[xDomainCalldataHash] = true; return; } xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /********************** * Internal Functions * **********************/ /** * Verifies that a received cross domain message is valid. * @return _valid Whether or not the message is valid. */ function _verifyXDomainMessage() view internal returns ( bool _valid ) { return ( iOVM_L1MessageSender( resolve("OVM_L1MessageSender") ).getL1MessageSender() == resolve("OVM_L1CrossDomainMessenger") ); } /** * Sends a cross domain message. * @param _message Message to send. * param _gasLimit Gas limit for the provided message. */ function _sendXDomainMessage( bytes memory _message, uint256 // _gasLimit ) internal { iOVM_L2ToL1MessagePasser(resolve("OVM_L2ToL1MessagePasser")).passMessageToL1(_message); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol"; /** * @title iOVM_L2CrossDomainMessenger */ interface iOVM_L2CrossDomainMessenger is iOVM_CrossDomainMessenger { /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_L1MessageSender */ interface iOVM_L1MessageSender { /******************** * Public Functions * ********************/ function getL1MessageSender() external view returns (address _l1MessageSender); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_L2ToL1MessagePasser */ interface iOVM_L2ToL1MessagePasser { /********** * Events * **********/ event L2ToL1Message( uint256 _nonce, address _sender, bytes _data ); /******************** * Public Functions * ********************/ function passMessageToL1(bytes calldata _message) external; } // 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.5.0 <0.8.0; /* Interface Imports */ import { iOVM_L2ToL1MessagePasser } from "../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol"; /** * @title OVM_L2ToL1MessagePasser * @dev The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of the * of a message on L2. The L1 Cross Domain Messenger performs this proof in its * _verifyStorageProof function, which verifies the existence of the transaction hash in this * contract's `sentMessages` mapping. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser { /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public sentMessages; /******************** * Public Functions * ********************/ /** * Passes a message to L1. * @param _message Message to pass to L1. */ function passMessageToL1( bytes memory _message ) override public { // Note: although this function is public, only messages sent from the // OVM_L2CrossDomainMessenger will be relayed by the OVM_L1CrossDomainMessenger. // This is enforced by a check in OVM_L1CrossDomainMessenger._verifyStorageProof(). sentMessages[keccak256( abi.encodePacked( _message, msg.sender ) )] = true; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_L1MessageSender } from "../../iOVM/predeploys/iOVM_L1MessageSender.sol"; import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; /** * @title OVM_L1MessageSender * @dev The L1MessageSender is a predeploy contract running on L2. During the execution of cross * domain transaction from L1 to L2, it returns the address of the L1 account (either an EOA or * contract) which sent the message to L2 via the Canonical Transaction Chain's `enqueue()` * function. * * This contract exclusively serves as a getter for the ovmL1TXORIGIN operation. This is necessary * because there is no corresponding operation in the EVM which the the optimistic solidity compiler * can be replaced with a call to the ExecutionManager's ovmL1TXORIGIN() function. * * * Compiler used: solc * Runtime target: OVM */ contract OVM_L1MessageSender is iOVM_L1MessageSender { /******************** * Public Functions * ********************/ /** * @return _l1MessageSender L1 message sender address (msg.sender). */ function getL1MessageSender() override public view returns ( address _l1MessageSender ) { // Note that on L2 msg.sender (ie. evmCALLER) will always be the Execution Manager return iOVM_ExecutionManager(msg.sender).ovmL1TXORIGIN(); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPReader.sol"; /** * @title TestLib_RLPReader */ contract TestLib_RLPReader { function readList( bytes memory _in ) public pure returns ( bytes[] memory ) { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_in); bytes[] memory out = new bytes[](decoded.length); for (uint256 i = 0; i < out.length; i++) { out[i] = Lib_RLPReader.readRawBytes(decoded[i]); } return out; } function readString( bytes memory _in ) public pure returns ( string memory ) { return Lib_RLPReader.readString(_in); } function readBytes( bytes memory _in ) public pure returns ( bytes memory ) { return Lib_RLPReader.readBytes(_in); } function readBytes32( bytes memory _in ) public pure returns ( bytes32 ) { return Lib_RLPReader.readBytes32(_in); } function readUint256( bytes memory _in ) public pure returns ( uint256 ) { return Lib_RLPReader.readUint256(_in); } function readBool( bytes memory _in ) public pure returns ( bool ) { return Lib_RLPReader.readBool(_in); } function readAddress( bytes memory _in ) public pure returns ( address ) { return Lib_RLPReader.readAddress(_in); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_MerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_MerkleTrie.sol"; /** * @title TestLib_MerkleTrie */ contract TestLib_MerkleTrie { function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bool ) { return Lib_MerkleTrie.verifyInclusionProof( _key, _value, _proof, _root ); } function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bytes32 ) { return Lib_MerkleTrie.update( _key, _value, _proof, _root ); } function get( bytes memory _key, bytes memory _proof, bytes32 _root ) public pure returns ( bool, bytes memory ) { return Lib_MerkleTrie.get( _key, _proof, _root ); } function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) public pure returns ( bytes32 ) { return Lib_MerkleTrie.getSingleNodeRootHash( _key, _value ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_SecureMerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_SecureMerkleTrie.sol"; /** * @title TestLib_SecureMerkleTrie */ contract TestLib_SecureMerkleTrie { function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bool ) { return Lib_SecureMerkleTrie.verifyInclusionProof( _key, _value, _proof, _root ); } function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bytes32 ) { return Lib_SecureMerkleTrie.update( _key, _value, _proof, _root ); } function get( bytes memory _key, bytes memory _proof, bytes32 _root ) public pure returns ( bool, bytes memory ) { return Lib_SecureMerkleTrie.get( _key, _proof, _root ); } function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) public pure returns ( bytes32 ) { return Lib_SecureMerkleTrie.getSingleNodeRootHash( _key, _value ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_ResolvedDelegateProxy */ contract Lib_ResolvedDelegateProxy { /************* * Variables * *************/ // Using mappings to store fields to avoid overwriting storage slots in the // implementation contract. For example, instead of storing these fields at // storage slot `0` & `1`, they are stored at `keccak256(key + slot)`. // See: https://solidity.readthedocs.io/en/v0.7.0/internals/layout_in_storage.html // NOTE: Do not use this code in your own contract system. // There is a known flaw in this contract, and we will remove it from the repository // in the near future. Due to the very limited way that we are using it, this flaw is // not an issue in our system. mapping (address => string) private implementationName; mapping (address => Lib_AddressManager) private addressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. * @param _implementationName implementationName of the contract to proxy to. */ constructor( address _libAddressManager, string memory _implementationName ) { addressManager[address(this)] = Lib_AddressManager(_libAddressManager); implementationName[address(this)] = _implementationName; } /********************* * Fallback Function * *********************/ fallback() external payable { address target = addressManager[address(this)].getAddress( (implementationName[address(this)]) ); require( target != address(0), "Target address must be initialized." ); (bool success, bytes memory returndata) = target.delegatecall(msg.data); if (success == true) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title OVM_GasPriceOracle * @dev This contract exposes the current l2 gas price, a measure of how congested the network * currently is. This measure is used by the Sequencer to determine what fee to charge for * transactions. When the system is more congested, the l2 gas price will increase and fees * will also increase as a result. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_GasPriceOracle is Ownable { /************* * Variables * *************/ // Current l2 gas price uint256 public gasPrice; /*************** * Constructor * ***************/ /** * @param _owner Address that will initially own this contract. */ constructor( address _owner, uint256 _initialGasPrice ) Ownable() { setGasPrice(_initialGasPrice); transferOwnership(_owner); } /******************** * Public Functions * ********************/ /** * Allows the owner to modify the l2 gas price. * @param _gasPrice New l2 gas price. */ function setGasPrice( uint256 _gasPrice ) public onlyOwner { gasPrice = _gasPrice; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Contract Imports */ import { L2StandardERC20 } from "../../../libraries/standards/L2StandardERC20.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; /** * @title OVM_L2StandardTokenFactory * @dev Factory contract for creating standard L2 token representations of L1 ERC20s * compatible with and working on the standard bridge. * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2StandardTokenFactory { event StandardL2TokenCreated(address indexed _l1Token, address indexed _l2Token); /** * @dev Creates an instance of the standard ERC20 token on L2. * @param _l1Token Address of the corresponding L1 token. * @param _name ERC20 name. * @param _symbol ERC20 symbol. */ function createStandardL2Token( address _l1Token, string memory _name, string memory _symbol ) external { require (_l1Token != address(0), "Must provide L1 token address"); L2StandardERC20 l2Token = new L2StandardERC20( Lib_PredeployAddresses.L2_STANDARD_BRIDGE, _l1Token, _name, _symbol ); emit StandardL2TokenCreated(_l1Token, address(l2Token)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../optimistic-ethereum/libraries/utils/Lib_Bytes32Utils.sol"; /** * @title TestLib_Byte32Utils */ contract TestLib_Bytes32Utils { function toBool( bytes32 _in ) public pure returns ( bool _out ) { return Lib_Bytes32Utils.toBool(_in); } function fromBool( bool _in ) public pure returns ( bytes32 _out ) { return Lib_Bytes32Utils.fromBool(_in); } function toAddress( bytes32 _in ) public pure returns ( address _out ) { return Lib_Bytes32Utils.toAddress(_in); } function fromAddress( address _in ) public pure returns ( bytes32 _out ) { return Lib_Bytes32Utils.fromAddress(_in); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EthUtils } from "../../optimistic-ethereum/libraries/utils/Lib_EthUtils.sol"; /** * @title TestLib_EthUtils */ contract TestLib_EthUtils { function getCode( address _address, uint256 _offset, uint256 _length ) public view returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _address, _offset, _length ); } function getCode( address _address ) public view returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _address ); } function getCodeSize( address _address ) public view returns ( uint256 _codeSize ) { return Lib_EthUtils.getCodeSize( _address ); } function getCodeHash( address _address ) public view returns ( bytes32 _codeHash ) { return Lib_EthUtils.getCodeHash( _address ); } function createContract( bytes memory _code ) public returns ( address _created ) { return Lib_EthUtils.createContract( _code ); } function getAddressForCREATE( address _creator, uint256 _nonce ) public pure returns ( address _address ) { return Lib_EthUtils.getAddressForCREATE( _creator, _nonce ); } function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) public pure returns (address _address) { return Lib_EthUtils.getAddressForCREATE2( _creator, _bytecode, _salt ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_MerkleTree } from "../../optimistic-ethereum/libraries/utils/Lib_MerkleTree.sol"; /** * @title TestLib_MerkleTree */ contract TestLib_MerkleTree { function getMerkleRoot( bytes32[] memory _elements ) public pure returns ( bytes32 ) { return Lib_MerkleTree.getMerkleRoot( _elements ); } function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) public pure returns ( bool ) { return Lib_MerkleTree.verify( _root, _leaf, _index, _siblings, _totalLeaves ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; /* Contract Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title mockOVM_BondManager */ contract mockOVM_BondManager is iOVM_BondManager, Lib_AddressResolver { constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) override public {} function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) override public {} function deposit() override public {} function startWithdrawal() override public {} function finalizeWithdrawal() override public {} function claim( address _who ) override public {} function isCollateralized( address _who ) override public view returns ( bool ) { // Only authenticate sequencer to submit state root batches. return _who == resolve("OVM_Proposer"); } function getGasSpent( bytes32, // _preStateRoot, address // _who ) override public pure returns ( uint256 ) { return 0; } }
@inheritdoc iOVM_L1StandardBridge/
function finalizeETHWithdrawal( address _from, address _to, uint256 _amount, bytes calldata _data ) external override onlyFromCrossDomainAccount(l2TokenBridge) { require(success, "TransferHelper::safeTransferETH: ETH transfer failed"); emit ETHWithdrawalFinalized(_from, _to, _amount, _data); }
6,166,864
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "./IERC20.sol"; import "./SafeERC20.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; import "./FOGToken.sol"; // FOGFarming is the master of FOG. He can make FOG and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. // // Have fun reading it. Hopefully it's bug-free. contract NoMist is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 mistRewardDebt; // extra reward debt // // We do some fancy math here. Basically, any point in time, the amount of FOGs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accFOGPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accFOGPerShare` (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. FOGs to distribute per block. uint256 lastRewardBlock; // Last block number that FOGs distribution occurs. uint256 accFOGPerShare; // Accumulated FOGs per share, times 1e12. See below. // extra pool reward uint256 mistPid; // PID for extra pool uint256 accMistPerShare; // Accumulated extra token per share, times 1e12. bool dualFarmingEnable; bool emergencyMode; } // The FOG TOKEN! FOGToken public fog; // Dev address. address public devaddr; // The block number when FOG mining starts. uint256 public startBlock; // Block number when test FOG period ends. uint256 public allEndBlock; // FOG tokens created per block. uint256 public fogPerBlock; // Max multiplier uint256 public maxMultiplier; // sc address for dual farming address public mistFarming; // the reward token for dual farming address public mist; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; uint256 public constant TEAM_PERCENT = 10; uint256 public constant PID_NOT_SET = 0xffffffff; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( FOGToken _fog, address _devaddr, uint256 _fogPerBlock, uint256 _startBlock, uint256 _allEndBlock, address _mistFarmingAddr, address _mistAddr ) { fog = _fog; devaddr = _devaddr; startBlock = _startBlock; allEndBlock = _allEndBlock; fogPerBlock = _fogPerBlock; maxMultiplier = 3e12; mistFarming = _mistFarmingAddr; mist = _mistAddr; } function setMistPid(uint _pid, uint _mistPid, bool _dualFarmingEnable) public onlyOwner { // only support set once if (poolInfo[_pid].mistPid == PID_NOT_SET) { poolInfo[_pid].mistPid = _mistPid; } poolInfo[_pid].dualFarmingEnable = _dualFarmingEnable; } function setMaxMultiplier(uint _maxMultiplier) public onlyOwner { maxMultiplier = _maxMultiplier; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint _mistPid, bool _dualFarmingEnable) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint mistPidUsed = PID_NOT_SET; if (_dualFarmingEnable) { mistPidUsed = _mistPid; } poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accFOGPerShare: 0, mistPid: mistPidUsed, accMistPerShare: 0, dualFarmingEnable: _dualFarmingEnable, emergencyMode: false })); } // Update the given pool's FOG 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; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_from >= allEndBlock) { return 0; } if (_to < startBlock) { return 0; } if (_to > allEndBlock && _from < startBlock) { return allEndBlock.sub(startBlock); } if (_to > allEndBlock) { return allEndBlock.sub(_from); } if (_from < startBlock) { return _to.sub(startBlock); } return _to.sub(_from); } // View function to see pending FOGs on frontend. function pendingFOG(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFOGPerShare = pool.accFOGPerShare; uint256 lpSupply; if (mistFarming == address(0) || !pool.dualFarmingEnable) { lpSupply = pool.lpToken.balanceOf(address(this)); } if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 fogReward = multiplier.mul(fogPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accFOGPerShare = accFOGPerShare.add(fogReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accFOGPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 lpSupply; if (mistFarming == address(0) || !pool.dualFarmingEnable) { lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { if (pool.lastRewardBlock < block.number) { pool.lastRewardBlock = block.number; } return; } } if (block.number <= pool.lastRewardBlock) { return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 fogReward = multiplier.mul(fogPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accFOGPerShare = pool.accFOGPerShare.add(fogReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to FOGFarming for FOG allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount.add(_amount) > 0) { uint256 pending = user.amount.mul(pool.accFOGPerShare).div(1e12).sub(user.rewardDebt); mintFOG(pending); safeFOGTransfer(msg.sender, pending); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accFOGPerShare).div(1e12); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from FOGFarming. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 pending = user.amount.mul(pool.accFOGPerShare).div(1e12).sub(user.rewardDebt); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accFOGPerShare).div(1e12); mintFOG(pending); safeFOGTransfer(msg.sender, pending); if (_amount > 0) { pool.lpToken.safeTransfer(address(msg.sender), _amount); } emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdrawEnable(uint256 _pid) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; pool.emergencyMode = true; pool.dualFarmingEnable = false; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.emergencyMode, "not enable emergence mode"); 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 FOG transfer function, just in case if rounding error causes pool to not have enough FOGs. function safeFOGTransfer(address _to, uint256 _amount) internal { uint256 fogBal = fog.balanceOf(address(this)); if (_amount > fogBal) { fog.transfer(_to, fogBal); } else { fog.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "Should be dev address"); devaddr = _devaddr; } function mintFOG(uint amount) private { fog.mint(devaddr, amount.mul(TEAM_PERCENT).div(100)); fog.mint(address(this), amount); } }
Deposit LP tokens to FOGFarming for FOG allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount.add(_amount) > 0) { uint256 pending = user.amount.mul(pool.accFOGPerShare).div(1e12).sub(user.rewardDebt); mintFOG(pending); safeFOGTransfer(msg.sender, pending); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accFOGPerShare).div(1e12); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); emit Deposit(msg.sender, _pid, _amount); }
5,513,589
pragma solidity ^0.4.24; // File: contracts\library\SafeMath.sol /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } // File: contracts\library\NameFilter.sol /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ &#169; Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } // File: contracts\library\MSFun.sol /** @title -MSFun- v0.2.4 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ &#169; Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ _ _ _ _ _ _ _ _ _ _ *=(_) _ _ (_)==========_(_)(_)(_)(_)_==========(_)(_)(_)(_)(_)================================* * (_)(_) (_)(_) (_) (_) (_) _ _ _ _ _ _ * (_) (_)_(_) (_) (_)_ _ _ _ (_) _ _ (_) (_) (_)(_)(_)(_)_ * (_) (_) (_) (_)(_)(_)(_)_ (_)(_)(_)(_) (_) (_) (_) * (_) (_) _ _ _ (_) _ _ (_) (_) (_) (_) (_) _ _ *=(_)=========(_)=(_)(_)==(_)_ _ _ _(_)=(_)(_)==(_)======(_)_ _ _(_)_ (_)========(_)=(_)(_)==* * (_) (_) (_)(_) (_)(_)(_)(_) (_)(_) (_) (_)(_)(_) (_)(_) (_) (_)(_) * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ * * ┌──────────────────────────────────────────────────────────────────────┐ * │ MSFun, is an importable library that gives your contract the ability │ * │ add multiSig requirement to functions. │ * └──────────────────────────────────────────────────────────────────────┘ * ┌────────────────────┐ * │ Setup Instructions │ * └────────────────────┘ * (Step 1) import the library into your contract * * import "./MSFun.sol"; * * (Step 2) set up the signature data for msFun * * MSFun.Data private msData; * ┌────────────────────┐ * │ Usage Instructions │ * └────────────────────┘ * at the beginning of a function * * function functionName() * { * if (MSFun.multiSig(msData, required signatures, "functionName") == true) * { * MSFun.deleteProposal(msData, "functionName"); * * // put function body here * } * } * ┌────────────────────────────────┐ * │ Optional Wrappers For TeamJust │ * └────────────────────────────────┘ * multiSig wrapper function (cuts down on inputs, improves readability) * this wrapper is HIGHLY recommended * * function multiSig(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredSignatures(), _whatFunction));} * function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));} * * wrapper for delete proposal (makes code cleaner) * * function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} * ┌────────────────────────────┐ * │ Utility & Vanity Functions │ * └────────────────────────────┘ * delete any proposal is highly recommended. without it, if an admin calls a multiSig * function, with argument inputs that the other admins do not agree upon, the function * can never be executed until the undesirable arguments are approved. * * function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} * * for viewing who has signed a proposal & proposal data * * function checkData(bytes32 _whatFunction) onlyAdmins() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} * * lets you check address of up to 3 signers (address) * * function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} * * same as above but will return names in string format. * * function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} * ┌──────────────────────────┐ * │ Functions In Depth Guide │ * └──────────────────────────┘ * In the following examples, the Data is the proposal set for this library. And * the bytes32 is the name of the function. * * MSFun.multiSig(Data, uint256, bytes32) - Manages creating/updating multiSig * proposal for the function being called. The uint256 is the required * number of signatures needed before the multiSig will return true. * Upon first call, multiSig will create a proposal and store the arguments * passed with the function call as msgData. Any admins trying to sign the * function call will need to send the same argument values. Once required * number of signatures is reached this will return a bool of true. * * MSFun.deleteProposal(Data, bytes32) - once multiSig unlocks the function body, * you will want to delete the proposal data. This does that. * * MSFun.checkMsgData(Data, bytes32) - checks the message data for any given proposal * * MSFun.checkCount(Data, bytes32) - checks the number of admins that have signed * the proposal * * MSFun.checkSigners(data, bytes32, uint256) - checks the address of a given signer. * the uint256, is the log number of the signer (ie 1st signer, 2nd signer) */ library MSFun { //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DATA SETS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // contact data setup struct Data { mapping (bytes32 => ProposalData) proposal_; } struct ProposalData { // a hash of msg.data bytes32 msgData; // number of signers uint256 count; // tracking of wither admins have signed mapping (address => bool) admin; // list of admins who have signed mapping (uint256 => address) log; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MULTI SIG FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction) internal returns(bool) { // our proposal key will be a hash of our function name + our contracts address // by adding our contracts address to this, we prevent anyone trying to circumvent // the proposal&#39;s security via external calls. bytes32 _whatProposal = whatProposal(_whatFunction); // this is just done to make the code more readable. grabs the signature count uint256 _currentCount = self.proposal_[_whatProposal].count; // store the address of the person sending the function call. we use msg.sender // here as a layer of security. in case someone imports our contract and tries to // circumvent function arguments. still though, our contract that imports this // library and calls multisig, needs to use onlyAdmin modifiers or anyone who // calls the function will be a signer. address _whichAdmin = msg.sender; // prepare our msg data. by storing this we are able to verify that all admins // are approving the same argument input to be executed for the function. we hash // it and store in bytes32 so its size is known and comparable bytes32 _msgData = keccak256(msg.data); // check to see if this is a new execution of this proposal or not if (_currentCount == 0) { // if it is, lets record the original signers data self.proposal_[_whatProposal].msgData = _msgData; // record original senders signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) // also useful if the calling function wants to give something to a // specific signer. self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; // if we now have enough signatures to execute the function, lets // return a bool of true. we put this here in case the required signatures // is set to 1. if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } // if its not the first execution, lets make sure the msgData matches } else if (self.proposal_[_whatProposal].msgData == _msgData) { // msgData is a match // make sure admin hasnt already signed if (self.proposal_[_whatProposal].admin[_whichAdmin] == false) { // record their signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; } // if we now have enough signatures to execute the function, lets // return a bool of true. // we put this here for a few reasons. (1) in normal operation, if // that last recorded signature got us to our required signatures. we // need to return bool of true. (2) if we have a situation where the // required number of signatures was adjusted to at or lower than our current // signature count, by putting this here, an admin who has already signed, // can call the function again to make it return a true bool. but only if // they submit the correct msg data if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } } // deletes proposal signature data after successfully executing a multiSig function function deleteProposal(Data storage self, bytes32 _whatFunction) internal { //done for readability sake bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; //delete the admins votes & log. i know for loops are terrible. but we have to do this //for our data stored in mappings. simply deleting the proposal itself wouldn&#39;t accomplish this. for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } //delete the rest of the data in the record delete self.proposal_[_whatProposal]; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // HELPER FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function whatProposal(bytes32 _whatFunction) private view returns(bytes32) { return(keccak256(abi.encodePacked(_whatFunction,this))); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // VANITY FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // returns a hashed version of msg.data sent by original signer for any given function function checkMsgData (Data storage self, bytes32 _whatFunction) internal view returns (bytes32 msg_data) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].msgData); } // returns number of signers for any given function function checkCount (Data storage self, bytes32 _whatFunction) internal view returns (uint256 signature_count) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].count); } // returns address of an admin who signed for any given function function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer) internal view returns (address signer) { require(_signer > 0, "MSFun checkSigner failed - 0 not allowed"); bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].log[_signer - 1]); } } // File: contracts\interface\TeamJustInterface.sol interface TeamJustInterface { function requiredSignatures() external view returns(uint256); function requiredDevSignatures() external view returns(uint256); function adminCount() external view returns(uint256); function devCount() external view returns(uint256); function adminName(address _who) external view returns(bytes32); function isAdmin(address _who) external view returns(bool); function isDev(address _who) external view returns(bool); } // File: contracts\interface\JIincForwarderInterface.sol interface JIincForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } // File: contracts\interface\PlayerBookReceiverInterface.sol interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } // File: contracts\PlayerBook.sol /* * -PlayerBook - v0.3.14 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ &#169; Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * ______ _ ______ _ *====(_____ \=| |===============================(____ \===============| |=============* * _____) )| | _____ _ _ _____ ____ ____) ) ___ ___ | | _ * | ____/ | | (____ || | | || ___ | / ___) | __ ( / _ \ / _ \ | |_/ ) * | | | | / ___ || |_| || ____|| | | |__) )| |_| || |_| || _ ( *====|_|=======\_)\_____|=\__ ||_____)|_|======|______/==\___/==\___/=|_|=\_)=========* * (____/ * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ contract PlayerBook { using NameFilter for string; using SafeMath for uint256; //TODO: address public affWallet = 0xeCd0D41045030e974C7b94a1C5CcB334D2E6a755; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it&#39;s simply locking our addresses, // PID&#39;s and names for referral codes. //TODO: plyr_[1].addr = 0x326d8d593195a3153f6d55d7791c10af9bcef597; plyr_[1].name = "justo"; plyr_[1].names = 1; pIDxAddr_[0x326d8d593195a3153f6d55d7791c10af9bcef597] = 1; pIDxName_["justo"] = 1; plyrNames_[1]["justo"] = true; plyrNameList_[1][1] = "justo"; plyr_[2].addr = 0x15B474F7DE7157FA0dB9FaaA8b82761E78E804B9; plyr_[2].name = "mantso"; plyr_[2].names = 1; pIDxAddr_[0x15B474F7DE7157FA0dB9FaaA8b82761E78E804B9] = 2; pIDxName_["mantso"] = 2; plyrNames_[2]["mantso"] = true; plyrNameList_[2][1] = "mantso"; plyr_[3].addr = 0xD3d96E74aFAE57B5191DC44Bdb08b037355523Ba; plyr_[3].name = "sumpunk"; plyr_[3].names = 1; pIDxAddr_[0xD3d96E74aFAE57B5191DC44Bdb08b037355523Ba] = 3; pIDxName_["sumpunk"] = 3; plyrNames_[3]["sumpunk"] = true; plyrNameList_[3][1] = "sumpunk"; plyr_[4].addr = 0x0c2d482FBc1da4DaCf3CD05b6A5955De1A296fa8; plyr_[4].name = "wang"; plyr_[4].names = 1; pIDxAddr_[0x0c2d482FBc1da4DaCf3CD05b6A5955De1A296fa8] = 4; pIDxName_["wang"] = 4; plyrNames_[4]["wang"] = true; plyrNameList_[4][1] = "wang"; pID_ = 4; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier onlyDevs() { //TODO: require( msg.sender == 0xE9675cdAf47bab3Eef5B1f1c2b7f8d41cDcf9b29 || msg.sender == 0x01910b43311806Ed713bdbB08113f2153769fFC1 , "only team just can activate" ); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you&#39;ve updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn&#39;t exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you&#39;ll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards //Jekyll_Island_Inc.deposit.value(address(this).balance)(); affWallet.transfer(address(this).balance); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } function setRegistrationFee(uint256 _fee) onlyDevs() public { registrationFee_ = _fee; } }
============================================================================== _ _ _|_ _ . _\(/_ | |_||_) .=============|================================================================
function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); }
8,075,894
pragma solidity ^0.4.23; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/investment/InvestmentAsset.sol"; import "../contracts/SwapyExchange.sol"; import "./helpers/ThrowProxy.sol"; import "./AssetCall.sol"; contract TestInvestmentAsset_marketplace { SwapyExchange protocol = SwapyExchange(DeployedAddresses.SwapyExchange()); address token = protocol.token(); bytes8 version = protocol.latestVersion(); address _library = protocol.getLibrary(version); InvestmentAsset assetInstance = new InvestmentAsset( _library, address(protocol), address(this), version, bytes5("USD"), uint256(500), uint256(360), uint256(10), token ); ThrowProxy throwProxy = new ThrowProxy(address(assetInstance)); AssetCall asset = new AssetCall(address(assetInstance)); AssetCall throwableAsset = new AssetCall(address(throwProxy)); // Truffle looks for `initialBalance` when it compiles the test suite // and funds this test contract with the specified amount on deployment. uint public initialBalance = 10 ether; function() payable public { } function shouldThrow(bool result) public { Assert.isFalse(result, "Should throw an exception"); } function testUnavailableActionsWhenInvested() public { asset.invest.value(1 ether)(false); withdrawFunds(address(assetInstance)); bool available = asset.sell(uint256(525)) && asset.cancelSellOrder() && asset.buy.value(1050 finney)(true) && asset.cancelSale() && asset.refuseSale() && asset.acceptSale(); Assert.isFalse(available, "Should not be executed"); } // Testing sell() function function testOnlyInvestorCanPutOnSale() public { bool result = throwableAsset.sell(uint256(525)); throwProxy.shouldThrow(); } function testInvestorCanPutOnSale() public { bool result = asset.sell(uint256(525)); Assert.equal(result, true, "Asset must be put up on sale"); InvestmentAsset.Status currentStatus = assetInstance.status(); bool isForSale = currentStatus == InvestmentAsset.Status.FOR_SALE; Assert.equal(isForSale, true, "The asset must be available on market place"); } function testUnavailableActionsWhenOnSale() public { bool available = asset.sell(uint256(525)) && asset.cancelSale() && asset.refuseSale() && asset.acceptSale(); Assert.isFalse(available, "Should not be executed"); } // Testing cancelSellOrder() function function testOnlyInvestorCanRemoveOnSale() public { bool result = throwableAsset.cancelSellOrder(); throwProxy.shouldThrow(); } function testInvestorCanRemoveOnSale() public { bool result = asset.cancelSellOrder(); Assert.equal(result, true, "Asset must be removed for sale"); InvestmentAsset.Status currentStatus = assetInstance.status(); bool isInvested = currentStatus == InvestmentAsset.Status.INVESTED; Assert.equal(isInvested, true, "The asset must be invested"); } // Testing buy() function function testBuyerAddressMustBeValid() { asset.sell(uint256(525)); bool result = throwableAsset.buy.value(1050 finney)(true); throwProxy.shouldThrow(); } function testUserCanBuyAsset() public { uint256 previousBalance = address(this).balance; uint256 previousAssetBalance = address(assetInstance).balance; bool result = asset.buy.value(1050 finney)(false); Assert.equal(result, true, "Asset must be bought"); InvestmentAsset.Status currentStatus = assetInstance.status(); bool isPendingSale = currentStatus == InvestmentAsset.Status.PENDING_INVESTOR_AGREEMENT; Assert.equal(isPendingSale, true, "The asset must be locked on market place"); Assert.equal( previousBalance - address(this).balance, address(assetInstance).balance - previousAssetBalance, "balance changes must be equal" ); } function testUnavailableActionsWhenPendingSale() public { bool available = withdrawFunds(address(assetInstance)) && asset.cancelInvestment() && asset.sell(uint256(525)) && asset.buy.value(1050 finney)(false); Assert.isFalse(available, "Should not be executed"); } // Testing cancelSale() function function testOnlyBuyerCanCancelPurchase() public { bool result = throwableAsset.cancelSale(); throwProxy.shouldThrow(); } function testBuyerCanCancelPurchase() public { bool result = asset.cancelSale(); Assert.equal(result, true, "Purchase must be canceled"); InvestmentAsset.Status currentStatus = assetInstance.status(); bool isForSale = currentStatus == InvestmentAsset.Status.FOR_SALE; Assert.equal(isForSale, true, "The asset must be available on market place"); } // Testing refuseSale() function function testOnlyInvestorCanRefusePurchase() public { asset.buy.value(1050 finney)(false); bool result = throwableAsset.refuseSale(); throwProxy.shouldThrow(); } function testInvestorCanRefusePurchase() public { bool result = asset.refuseSale(); Assert.equal(result, true, "Purchase must be refused"); InvestmentAsset.Status currentStatus = assetInstance.status(); bool isForSale = currentStatus == InvestmentAsset.Status.FOR_SALE; Assert.equal(isForSale, true, "The asset must be available on market place"); } // Testing acceptSale() function function testOnlyInvestorCanAcceptSale() public { asset.buy.value(1050 finney)(false); bool result = throwableAsset.acceptSale(); throwProxy.shouldThrow(); } function testInvestorCanAcceptSale() public { uint256 previousBalance = address(asset).balance; uint256 previousAssetBalance = address(assetInstance).balance; bool result = asset.acceptSale(); Assert.equal(result, true, "Sale must be accepted"); InvestmentAsset.Status currentStatus = assetInstance.status(); bool isInvested = currentStatus == InvestmentAsset.Status.INVESTED; Assert.equal(isInvested, true, "The asset must be invested"); Assert.equal( address(asset).balance - previousBalance, previousAssetBalance - address(assetInstance).balance, "balance changes must be equal" ); } function withdrawFunds(address _asset) returns(bool) { return _asset.call(abi.encodeWithSignature("withdrawFunds()")); } }
Testing acceptSale() function
function testOnlyInvestorCanAcceptSale() public { asset.buy.value(1050 finney)(false); bool result = throwableAsset.acceptSale(); throwProxy.shouldThrow(); }
6,385,787
//Address: 0x74384b6355ad7892c7be6cb524d72768a3883f0c //Contract name: REDCrowdfund //Balance: 0 Ether //Verification Date: 1/9/2018 //Transacion Count: 263 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract REDToken is ERC20, Ownable { using SafeMath for uint; /*----------------- Token Information -----------------*/ string public constant name = "Red Community Token"; string public constant symbol = "RED"; uint8 public decimals = 18; // (ERC20 API) Decimal precision, factor is 1e18 mapping (address => uint256) angels; // Angels accounts table (during locking period only) mapping (address => uint256) accounts; // User's accounts table mapping (address => mapping (address => uint256)) allowed; // User's allowances table /*----------------- ICO Information -----------------*/ uint256 public angelSupply; // Angels sale supply uint256 public earlyBirdsSupply; // Early birds supply uint256 public publicSupply; // Open round supply uint256 public foundationSupply; // Red Foundation/Community supply uint256 public redTeamSupply; // Red team supply uint256 public marketingSupply; // Marketing & strategic supply uint256 public angelAmountRemaining; // Amount of private angels tokens remaining at a given time uint256 public icoStartsAt; // Crowdsale ending timestamp uint256 public icoEndsAt; // Crowdsale ending timestamp uint256 public redTeamLockingPeriod; // Locking period for Red team's supply uint256 public angelLockingPeriod; // Locking period for Angel's supply address public crowdfundAddress; // Crowdfunding contract address address public redTeamAddress; // Red team address address public foundationAddress; // Foundation address address public marketingAddress; // Private equity address bool public unlock20Done = false; // Allows the 20% unlocking for angels only once enum icoStages { Ready, // Initial state on contract's creation EarlyBirds, // Early birds state PublicSale, // Public crowdsale state Done // Ending state after ICO } icoStages stage; // Crowdfunding current state /*----------------- Events -----------------*/ event EarlyBirdsFinalized(uint tokensRemaining); // Event called when early birds round is done event CrowdfundFinalized(uint tokensRemaining); // Event called when crowdfund is done /*----------------- Modifiers -----------------*/ modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier onlyDuringCrowdfund(){ // Ensures actions can only happen after crowdfund ends require((now >= icoStartsAt) && (now < icoEndsAt)); _; } modifier notBeforeCrowdfundEnds(){ // Ensures actions can only happen after crowdfund ends require(now >= icoEndsAt); _; } modifier checkRedTeamLockingPeriod() { // Ensures locking period is over require(now >= redTeamLockingPeriod); _; } modifier checkAngelsLockingPeriod() { // Ensures locking period is over require(now >= angelLockingPeriod); _; } modifier onlyCrowdfund() { // Ensures only crowdfund can call the function require(msg.sender == crowdfundAddress); _; } /*----------------- ERC20 API -----------------*/ // ------------------------------------------------- // Transfers amount to address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public notBeforeCrowdfundEnds returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfered addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public notBeforeCrowdfundEnds returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of RED // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's RED allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the RED balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner] + angels[_owner]; } /*----------------- Token API -----------------*/ // ------------------------------------------------- // Contract's constructor // ------------------------------------------------- function REDToken() public { totalSupply = 200000000 * 1e18; // 100% - 200 million total RED with 18 decimals angelSupply = 20000000 * 1e18; // 10% - 20 million RED for private angels sale earlyBirdsSupply = 48000000 * 1e18; // 24% - 48 million RED for early-bird sale publicSupply = 12000000 * 1e18; // 6% - 12 million RED for the public crowdsale redTeamSupply = 30000000 * 1e18; // 15% - 30 million RED for Red team foundationSupply = 70000000 * 1e18; // 35% - 70 million RED for foundation/incentivising efforts marketingSupply = 20000000 * 1e18; // 10% - 20 million RED for covering marketing and strategic expenses angelAmountRemaining = angelSupply; // Decreased over the course of the private angel sale redTeamAddress = 0x31aa507c140E012d0DcAf041d482e04F36323B03; // Red Team address foundationAddress = 0x93e3AF42939C163Ee4146F63646Fb4C286CDbFeC; // Foundation/Community address marketingAddress = 0x0; // Marketing/Strategic address icoStartsAt = 1515398400; // Jan 8th 2018, 16:00, GMT+8 icoEndsAt = 1517385600; // Jan 31th 2018, 16:00, GMT+8 angelLockingPeriod = icoEndsAt.add(90 days); // 3 months locking period redTeamLockingPeriod = icoEndsAt.add(365 days); // 12 months locking period addToBalance(foundationAddress, foundationSupply); stage = icoStages.Ready; // Initializes state } // ------------------------------------------------- // Opens early birds sale // ------------------------------------------------- function startCrowdfund() external onlyCrowdfund onlyDuringCrowdfund returns(bool) { require(stage == icoStages.Ready); stage = icoStages.EarlyBirds; addToBalance(crowdfundAddress, earlyBirdsSupply); return true; } // ------------------------------------------------- // Returns TRUE if early birds round is currently going on // ------------------------------------------------- function isEarlyBirdsStage() external view returns(bool) { return (stage == icoStages.EarlyBirds); } // ------------------------------------------------- // Sets the crowdfund address, can only be done once // ------------------------------------------------- function setCrowdfundAddress(address _crowdfundAddress) external onlyOwner nonZeroAddress(_crowdfundAddress) { require(crowdfundAddress == 0x0); crowdfundAddress = _crowdfundAddress; } // ------------------------------------------------- // Function for the Crowdfund to transfer tokens // ------------------------------------------------- function transferFromCrowdfund(address _to, uint256 _amount) external onlyCrowdfund nonZeroAmount(_amount) nonZeroAddress(_to) returns (bool success) { require(balanceOf(crowdfundAddress) >= _amount); decrementBalance(crowdfundAddress, _amount); addToBalance(_to, _amount); Transfer(0x0, _to, _amount); return true; } // ------------------------------------------------- // Releases Red team supply after locking period is passed // ------------------------------------------------- function releaseRedTeamTokens() external checkRedTeamLockingPeriod onlyOwner returns(bool success) { require(redTeamSupply > 0); addToBalance(redTeamAddress, redTeamSupply); Transfer(0x0, redTeamAddress, redTeamSupply); redTeamSupply = 0; return true; } // ------------------------------------------------- // Releases Marketing & strategic supply // ------------------------------------------------- function releaseMarketingTokens() external onlyOwner returns(bool success) { require(marketingSupply > 0); addToBalance(marketingAddress, marketingSupply); Transfer(0x0, marketingAddress, marketingSupply); marketingSupply = 0; return true; } // ------------------------------------------------- // Finalizes early birds round. If some RED are left, let them overflow to the crowdfund // ------------------------------------------------- function finalizeEarlyBirds() external onlyOwner returns (bool success) { require(stage == icoStages.EarlyBirds); uint256 amount = balanceOf(crowdfundAddress); addToBalance(crowdfundAddress, publicSupply); stage = icoStages.PublicSale; EarlyBirdsFinalized(amount); // event log return true; } // ------------------------------------------------- // Finalizes crowdfund. If there are leftover RED, let them overflow to foundation // ------------------------------------------------- function finalizeCrowdfund() external onlyCrowdfund { require(stage == icoStages.PublicSale); uint256 amount = balanceOf(crowdfundAddress); if (amount > 0) { accounts[crowdfundAddress] = 0; addToBalance(foundationAddress, amount); Transfer(crowdfundAddress, foundationAddress, amount); } stage = icoStages.Done; CrowdfundFinalized(amount); // event log } // ------------------------------------------------- // Changes Red Team wallet // ------------------------------------------------- function changeRedTeamAddress(address _wallet) external onlyOwner { redTeamAddress = _wallet; } // ------------------------------------------------- // Changes Marketing&Strategic wallet // ------------------------------------------------- function changeMarketingAddress(address _wallet) external onlyOwner { marketingAddress = _wallet; } // ------------------------------------------------- // Function to unlock 20% RED to private angels investors // ------------------------------------------------- function partialUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner notBeforeCrowdfundEnds returns (bool success) { require(unlock20Done == false); uint256 amount; address holder; for (uint256 i = 0; i < _batchOfAddresses.length; i++) { holder = _batchOfAddresses[i]; amount = angels[holder].mul(20).div(100); angels[holder] = angels[holder].sub(amount); addToBalance(holder, amount); } unlock20Done = true; return true; } // ------------------------------------------------- // Function to unlock all remaining RED to private angels investors (after 3 months) // ------------------------------------------------- function fullUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner checkAngelsLockingPeriod returns (bool success) { uint256 amount; address holder; for (uint256 i = 0; i < _batchOfAddresses.length; i++) { holder = _batchOfAddresses[i]; amount = angels[holder]; angels[holder] = 0; addToBalance(holder, amount); } return true; } // ------------------------------------------------- // Function to reserve RED to private angels investors (initially locked) // the amount of RED is in Wei // ------------------------------------------------- function deliverAngelsREDAccounts(address[] _batchOfAddresses, uint[] _amountOfRED) external onlyOwner onlyDuringCrowdfund returns (bool success) { for (uint256 i = 0; i < _batchOfAddresses.length; i++) { deliverAngelsREDBalance(_batchOfAddresses[i], _amountOfRED[i]); } return true; } /*----------------- Helper functions -----------------*/ // ------------------------------------------------- // If one address has contributed more than once, // the contributions will be aggregated // ------------------------------------------------- function deliverAngelsREDBalance(address _accountHolder, uint _amountOfBoughtRED) internal onlyOwner { require(angelAmountRemaining > 0); angels[_accountHolder] = angels[_accountHolder].add(_amountOfBoughtRED); Transfer(0x0, _accountHolder, _amountOfBoughtRED); angelAmountRemaining = angelAmountRemaining.sub(_amountOfBoughtRED); } // ------------------------------------------------- // Adds to balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Removes from balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } } contract REDCrowdfund is Ownable { using SafeMath for uint; mapping (address => bool) whiteList; // Buyers whitelisting mapping bool public isOpen = false; // Is the crowd fund open? address public tokenAddress; // Address of the deployed RED token contract address public wallet; // Address of secure wallet to receive crowdfund contributions uint256 public weiRaised = 0; uint256 public startsAt; // Crowdfund starting time (Epoch format) uint256 public endsAt; // Crowdfund ending time (Epoch format) REDToken public RED; // Instance of the RED token contract /*----------------- Events -----------------*/ event WalletAddressChanged(address _wallet); // Triggered upon owner changing the wallet address event AmountRaised(address beneficiary, uint amountRaised); // Triggered upon crowdfund being finalized event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); // Triggered upon purchasing tokens /*----------------- Modifiers -----------------*/ modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier crowdfundIsActive() { // Ensures the crowdfund is ongoing require(isOpen && now >= startsAt && now <= endsAt); _; } modifier notBeforeCrowdfundEnds(){ // Ensures actions can only happen after crowdfund ends require(now >= endsAt); _; } modifier onlyWhiteList() { // Ensures only whitelisted address can buy tokens require(whiteList[msg.sender]); _; } /*----------------- Crowdfunding API -----------------*/ // ------------------------------------------------- // Contract's constructor // ------------------------------------------------- function REDCrowdfund(address _tokenAddress) public { wallet = 0xc65f0d8a880f3145157117Af73fe2e6e8E60eF3c; // ICO wallet address startsAt = 1515398400; // Jan 8th 2018, 16:00, GMT+8 endsAt = 1517385600; // Jan 31th 2018, 16:00, GMT+8 tokenAddress = _tokenAddress; // RED token Address RED = REDToken(tokenAddress); } // ------------------------------------------------- // Changes main contribution wallet // ------------------------------------------------- function changeWalletAddress(address _wallet) external onlyOwner { wallet = _wallet; WalletAddressChanged(_wallet); } // ------------------------------------------------- // Opens the crowdfunding // ------------------------------------------------- function openCrowdfund() external onlyOwner returns (bool success) { require(isOpen == false); RED.startCrowdfund(); isOpen = true; return true; } // ------------------------------------------------- // Function to buy RED. One can also buy RED by calling this function directly and send // it to another destination. // ------------------------------------------------- function buyTokens(address _to) public crowdfundIsActive onlyWhiteList nonZeroAddress(_to) nonZeroValue payable { uint256 weiAmount = msg.value; uint256 tokens; uint price = 2500; if (RED.isEarlyBirdsStage()) {price = 2750;} // 10% discount for early birds tokens = weiAmount * price; weiRaised = weiRaised.add(weiAmount); wallet.transfer(weiAmount); if (!RED.transferFromCrowdfund(_to, tokens)) {revert();} TokenPurchase(_to, weiAmount, tokens); } // ------------------------------------------------- // Closes the crowdfunding. Any unsold RED will go back to the foundation. // ------------------------------------------------- function closeCrowdfund() external notBeforeCrowdfundEnds onlyOwner returns (bool success) { AmountRaised(wallet, weiRaised); RED.finalizeCrowdfund(); isOpen = false; return true; } // ------------------------------------------------- // Function to whitelist buyers // ------------------------------------------------- function whitelistAccounts(address[] _batchOfAddresses) external onlyOwner returns (bool success) { for (uint256 i = 0; i < _batchOfAddresses.length; i++) { whiteList[_batchOfAddresses[i]] = true; } return true; } /*----------------- Entry point -----------------*/ // ------------------------------------------------- // To contribute, send a value transaction to the crowdfund address. // Please include at least 100000 gas. // ------------------------------------------------- function () public payable { buyTokens(msg.sender); } }
------------------------------------------------- Transfers from one address to another (need allowance to be called first) -------------------------------------------------
function transferFrom(address _from, address _to, uint256 _amount) public notBeforeCrowdfundEnds returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; }
5,346,884
/** *Submitted for verification at Etherscan.io on 2021-02-06 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint a, uint b) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b <= a, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint 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(uint a, uint b) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/protocol/IStrategy.sol /* version 1.2.0 Changes Changes listed here do not affect interaction with other contracts (Vault and Controller) - removed function assets(address _token) external view returns (bool); - remove function deposit(uint), declared in IStrategyERC20 - add function setSlippage(uint _slippage); - add function setDelta(uint _delta); */ interface IStrategy { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying asset (ETH or ERC20) @dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy */ function underlying() external view returns (address); /* @notice Returns total amount of underlying transferred from vault */ function totalDebt() external view returns (uint); function performanceFee() external view returns (uint); function slippage() external view returns (uint); /* @notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN */ function delta() external view returns (uint); /* @dev Flag to force exit in case normal exit fails */ function forceExit() external view returns (bool); function setAdmin(address _admin) external; function setController(address _controller) external; function setPerformanceFee(uint _fee) external; function setSlippage(uint _slippage) external; function setDelta(uint _delta) external; function setForceExit(bool _forceExit) external; /* @notice Returns amount of underlying asset locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying asset is invested */ function totalAssets() external view returns (uint); /* @notice Withdraw `_amount` underlying asset @param amount Amount of underlying asset to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying asset from strategy */ function withdrawAll() external; /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external; /* @notice Exit from strategy @dev Must transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer @dev _token must not be equal to underlying token */ function sweep(address _token) external; } // File: contracts/protocol/IStrategyETH.sol interface IStrategyETH is IStrategy { /* @notice Deposit ETH */ function deposit() external payable; } // File: contracts/protocol/IController.sol interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // File: contracts/StrategyETH.sol /* version 1.2.0 */ // used inside harvest abstract contract StrategyETH is IStrategyETH { using SafeERC20 for IERC20; using SafeMath for uint; address public override admin; address public override controller; address public immutable override vault; // Placeholder address to indicate that this is ETH strategy address public constant override underlying = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // total amount of ETH transferred from vault uint public override totalDebt; // performance fee sent to treasury when harvest() generates profit uint public override performanceFee = 500; uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee uint internal constant PERFORMANCE_FEE_MAX = 10000; // prevent slippage from deposit / withdraw uint public override slippage = 100; uint internal constant SLIPPAGE_MAX = 10000; /* Multiplier used to check totalAssets() is <= total debt * delta / DELTA_MIN */ uint public override delta = 10050; uint private constant DELTA_MIN = 10000; // Force exit, in case normal exit fails bool public override forceExit; constructor(address _controller, address _vault) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); admin = msg.sender; controller = _controller; vault = _vault; } /* @dev implement receive() external payable in child contract @dev receive() should restrict msg.sender to prevent accidental ETH transfer @dev vault and controller will never call receive() */ modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault, "!authorized" ); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setPerformanceFee(uint _fee) external override onlyAdmin { require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap"); performanceFee = _fee; } function setSlippage(uint _slippage) external override onlyAdmin { require(_slippage <= SLIPPAGE_MAX, "slippage > max"); slippage = _slippage; } function setDelta(uint _delta) external override onlyAdmin { require(_delta >= DELTA_MIN, "delta < min"); delta = _delta; } function setForceExit(bool _forceExit) external override onlyAdmin { forceExit = _forceExit; } function _sendEthToVault(uint _amount) internal { require(address(this).balance >= _amount, "ETH balance < amount"); (bool sent, ) = vault.call{value: _amount}(""); require(sent, "Send ETH failed"); } function _increaseDebt(uint _ethAmount) private { totalDebt = totalDebt.add(_ethAmount); } function _decreaseDebt(uint _ethAmount) private { _sendEthToVault(_ethAmount); if (_ethAmount > totalDebt) { totalDebt = 0; } else { totalDebt -= _ethAmount; } } function _totalAssets() internal view virtual returns (uint); /* @notice Returns amount of ETH locked in this contract */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _deposit() internal virtual; /* @notice Deposit ETH into this strategy */ function deposit() external payable override onlyAuthorized { require(msg.value > 0, "deposit = 0"); _increaseDebt(msg.value); _deposit(); } /* @notice Returns total shares owned by this contract for depositing ETH into external Defi */ function _getTotalShares() internal view virtual returns (uint); function _getShares(uint _ethAmount, uint _totalEth) internal view returns (uint) { /* calculate shares to withdraw w = amount of ETH to withdraw E = total redeemable ETH s = shares to withdraw P = total shares deposited into external liquidity pool w / E = s / P s = w / E * P */ if (_totalEth > 0) { uint totalShares = _getTotalShares(); return _ethAmount.mul(totalShares) / _totalEth; } return 0; } function _withdraw(uint _shares) internal virtual; /* @notice Withdraw ETH to vault @param _ethAmount Amount of ETH to withdraw @dev Caller should implement guard against slippage */ function withdraw(uint _ethAmount) external override onlyAuthorized { require(_ethAmount > 0, "withdraw = 0"); uint totalEth = _totalAssets(); require(_ethAmount <= totalEth, "withdraw > total"); uint shares = _getShares(_ethAmount, totalEth); if (shares > 0) { _withdraw(shares); } // transfer ETH to vault uint ethBal = address(this).balance; if (ethBal > 0) { _decreaseDebt(ethBal); } } function _withdrawAll() internal { uint totalShares = _getTotalShares(); if (totalShares > 0) { _withdraw(totalShares); } // transfer ETH to vault uint ethBal = address(this).balance; if (ethBal > 0) { _decreaseDebt(ethBal); totalDebt = 0; } } /* @notice Withdraw all ETH to vault @dev Caller should implement guard agains slippage */ function withdrawAll() external override onlyAuthorized { _withdrawAll(); } /* @notice Sell any staking rewards for ETH and then deposit ETH */ function harvest() external virtual override; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external override onlyAuthorized { uint totalEth = _totalAssets(); require(totalEth > totalDebt, "total ETH < debt"); uint profit = totalEth - totalDebt; // protect against price manipulation uint max = totalDebt.mul(delta) / DELTA_MIN; if (totalEth <= max) { /* total ETH is within reasonable bounds, probaly no price manipulation occured. */ /* If we were to withdraw profit followed by deposit, this would increase the total debt roughly by the profit. Withdrawing consumes high gas, so here we omit it and directly increase debt, as if withdraw and deposit were called. */ totalDebt = totalDebt.add(profit); } else { /* Possible reasons for total ETH > max 1. total debt = 0 2. total ETH really did increase over max 3. price was manipulated */ uint shares = _getShares(profit, totalEth); if (shares > 0) { uint balBefore = address(this).balance; _withdraw(shares); uint balAfter = address(this).balance; uint diff = balAfter.sub(balBefore); if (diff > 0) { _sendEthToVault(diff); } } } } function exit() external virtual override; function sweep(address) external virtual override; } // File: contracts/interfaces/uniswap/Uniswap.sol interface Uniswap { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactTokensForETH( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File: contracts/interfaces/curve/LiquidityGaugeV2.sol interface LiquidityGaugeV2 { function deposit(uint) external; function balanceOf(address) external view returns (uint); function withdraw(uint) external; function claim_rewards() external; } // File: contracts/interfaces/curve/Minter.sol // https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy interface Minter { function mint(address) external; } // File: contracts/interfaces/curve/StableSwapSTETH.sol interface StableSwapSTETH { function get_virtual_price() external view returns (uint); /* 0 ETH 1 STETH */ function balances(uint _index) external view returns (uint); function add_liquidity(uint[2] memory amounts, uint min) external payable; function remove_liquidity_one_coin( uint _token_amount, int128 i, uint min_amount ) external; } // File: contracts/interfaces/lido/StETH.sol interface StETH { function submit(address) external payable returns (uint); } // File: contracts/strategies/StrategyStEth.sol contract StrategyStEth is StrategyETH { // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Curve // // liquidity provider token (Curve ETH/STETH) address private constant LP = 0x06325440D014e39736583c165C2963BA99fAf14E; // StableSwapSTETH address private constant POOL = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LiquidityGaugeV2 address private constant GAUGE = 0x182B723a58739a9c974cFDB385ceaDb237453c28; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; // LIDO // address private constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; address private constant LDO = 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32; constructor(address _controller, address _vault) public StrategyETH(_controller, _vault) { // These tokens are never held by this contract // so the risk of them being stolen is minimal IERC20(CRV).safeApprove(UNISWAP, uint(-1)); // Minted on Gauge deposit, withdraw and claim_rewards // only this contract can spend on UNISWAP IERC20(LDO).safeApprove(UNISWAP, uint(-1)); } receive() external payable { // Don't allow vault to accidentally send ETH require(msg.sender != vault, "msg.sender == vault"); } function _totalAssets() internal view override returns (uint) { uint shares = LiquidityGaugeV2(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); return shares.mul(pricePerShare) / 1e18; } function _getStEthDepositAmount(uint _ethBal) private view returns (uint) { /* Goal is to find a0 and a1 such that b0 + a0 is close to b1 + a1 E = amount of ETH b0 = balance of ETH in Curve b1 = balance of stETH in Curve a0 = amount of ETH to deposit into Curve a1 = amount of stETH to deposit into Curve d = |b0 - b1| if d >= E if b0 >= b1 a0 = 0 a1 = E else a0 = E a1 = 0 else if b0 >= b1 # add d to balance Curve pool, plus half of remaining a1 = d + (E - d) / 2 = (E + d) / 2 a0 = E - a1 else a0 = (E + d) / 2 a1 = E - a0 */ uint[2] memory balances; balances[0] = StableSwapSTETH(POOL).balances(0); balances[1] = StableSwapSTETH(POOL).balances(1); uint diff; if (balances[0] >= balances[1]) { diff = balances[0] - balances[1]; } else { diff = balances[1] - balances[0]; } // a0 = ETH amount is ignored, recomputed after stEth is bought // a1 = stETH amount uint a1; if (diff >= _ethBal) { if (balances[0] >= balances[1]) { a1 = _ethBal; } } else { if (balances[0] >= balances[1]) { a1 = (_ethBal.add(diff)) / 2; } else { a1 = _ethBal.sub((_ethBal.add(diff)) / 2); } } // a0 is ignored, recomputed after stEth is bought return a1; } /* @notice Deposits ETH to LiquidityGaugeV2 */ function _deposit() internal override { uint bal = address(this).balance; if (bal > 0) { uint stEthAmount = _getStEthDepositAmount(bal); if (stEthAmount > 0) { StETH(ST_ETH).submit{value: stEthAmount}(address(this)); } uint ethBal = address(this).balance; uint stEthBal = IERC20(ST_ETH).balanceOf(address(this)); if (stEthBal > 0) { // ST_ETH is proxy so don't allow infinite approval IERC20(ST_ETH).safeApprove(POOL, stEthBal); } /* shares = eth amount * 1e18 / price per share */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint shares = bal.mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).add_liquidity{value: ethBal}([ethBal, stEthBal], min); } // stake into LiquidityGaugeV2 uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGaugeV2(GAUGE).deposit(lpBal); } } function _getTotalShares() internal view override returns (uint) { return LiquidityGaugeV2(GAUGE).balanceOf(address(this)); } function _withdraw(uint _lpAmount) internal override { // withdraw LP from LiquidityGaugeV2 LiquidityGaugeV2(GAUGE).withdraw(_lpAmount); uint lpBal = IERC20(LP).balanceOf(address(this)); /* eth amount = (shares * price per shares) / 1e18 */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint ethAmount = lpBal.mul(pricePerShare) / 1e18; uint min = ethAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).remove_liquidity_one_coin(lpBal, 0, min); // Now we have ETH } /* @dev Uniswap fails with zero address so no check is necessary here */ function _swapToEth(address _from, uint _amount) private { // create dynamic array with 2 elements address[] memory path = new address[](2); path[0] = _from; path[1] = WETH; Uniswap(UNISWAP).swapExactTokensForETH( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards() private { // claim LDO LiquidityGaugeV2(GAUGE).claim_rewards(); // claim CRV Minter(MINTER).mint(GAUGE); // Infinity approval for Uniswap set inside constructor uint ldoBal = IERC20(LDO).balanceOf(address(this)); if (ldoBal > 0) { _swapToEth(LDO, ldoBal); } uint crvBal = IERC20(CRV).balanceOf(address(this)); if (crvBal > 0) { _swapToEth(CRV, crvBal); } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { _claimRewards(); uint bal = address(this).balance; if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); // treasury must be able to receive ETH (bool sent, ) = treasury.call{value: fee}(""); require(sent, "Send ETH failed"); } _deposit(); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != GAUGE, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } }
/ ST_ETH is proxy so don't allow infinite approval
function _deposit() internal override { uint bal = address(this).balance; if (bal > 0) { uint stEthAmount = _getStEthDepositAmount(bal); if (stEthAmount > 0) { } uint ethBal = address(this).balance; uint stEthBal = IERC20(ST_ETH).balanceOf(address(this)); if (stEthBal > 0) { IERC20(ST_ETH).safeApprove(POOL, stEthBal); } uint shares = bal.mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; } if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGaugeV2(GAUGE).deposit(lpBal); } }
2,460,611
pragma solidity ^0.4.13; contract token { function transfer(address receiver, uint amount); function balanceOf(address _owner) constant returns (uint256 balance); } contract Presale { address public beneficiary; uint public min_fundingGoal; uint public max_fundingGoal; uint public amountRaised; uint public deadline; uint public rate; token public tokenReward; mapping(address => uint256) public balanceOf; bool fundingGoalReached = false; event GoalReached(address beneficiary, uint amountRaised); event FundTransfer(address backer, uint amount, bool isContribution); bool crowdsaleClosed = false; /* data structure to hold information about campaign contributors */ /* at initialization, setup the owner */ function Presale() { beneficiary = msg.sender; min_fundingGoal = 100 * 1 ether; max_fundingGoal = 2000 * 1 ether; deadline = now + 30 * 1 days; rate = 1500; // Each ether exchange for 1500.00000000 PAT tokenReward = token(0x990da731331aE62c3e8f3f73cB4ebeb6F082Bc7c); } /* The function without name is the default function that is called whenever anyone sends funds to a contract */ function () payable { uint amount = msg.value; require (!crowdsaleClosed); require (amountRaised + amount <= max_fundingGoal); require (amount >= 10 * 1 ether); balanceOf[msg.sender] += amount; amountRaised += amount; tokenReward.transfer(msg.sender, amount * rate * 10 ** 8 / 1 ether); FundTransfer(msg.sender, amount, true); } modifier afterDeadline() { if (now >= deadline) _; } /* checks if the goal or time limit has been reached and ends the campaign */ function checkGoalReached() afterDeadline { if (amountRaised >= min_fundingGoal){ fundingGoalReached = true; GoalReached(beneficiary, amountRaised); } crowdsaleClosed = true; } function safeWithdrawal() afterDeadline { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { FundTransfer(msg.sender, amount, false); } else { balanceOf[msg.sender] = amount; } } } if (fundingGoalReached && beneficiary == msg.sender) { if (beneficiary.send(amountRaised)) { FundTransfer(beneficiary, amountRaised, false); } else { //If we fail to send the funds to beneficiary, unlock funders balance fundingGoalReached = false; } } } function WithdrawlRemainingPAT() afterDeadline { require(msg.sender == beneficiary); uint remainingAmount = tokenReward.balanceOf(this); remainingAmount = remainingAmount * 99 / 100; tokenReward.transfer(beneficiary, remainingAmount); FundTransfer(beneficiary, remainingAmount, false); } }
If we fail to send the funds to beneficiary, unlock funders balance
function safeWithdrawal() afterDeadline { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { FundTransfer(msg.sender, amount, false); balanceOf[msg.sender] = amount; } } } if (fundingGoalReached && beneficiary == msg.sender) { if (beneficiary.send(amountRaised)) { FundTransfer(beneficiary, amountRaised, false); fundingGoalReached = false; } } }
10,699,921
./full_match/1/0x3C6FBc94288f5af5201085948DdB18aDED2E6879/sources/contracts/ApeFiNFT.sol
Admin sets the base URI. baseURI The base URI/
function setBaseURI(string memory baseURI) external onlyOwner { require(bytes(baseURI).length != 0, "empty base URI"); _baseURIExtended = baseURI; }
3,053,478
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; import "../../errors.sol"; import "./IURIBuilder.sol"; import "../Property.sol"; import "./TraitSet.sol"; import "../../utils/Random.sol"; contract Ship is Property { struct ShipParams { uint128 base; uint8 flags; uint8 maxHealth; uint8 minHealth; uint8 maxSpeed; uint8 minSpeed; uint248 gilding; uint8 sails; } mapping(uint256 => ShipParams) private _params; mapping(uint256 => TraitSet) private _traits; IURIBuilder private _uriBuilder; /// @custom:oz-upgrades-unsafe-allow constructor // solhint-disable-next-line no-empty-blocks constructor() initializer {} function initialize(Tier[5] calldata tiers) public initializer { __Property_init("Ship", "SHIP", tiers); _params[1] = ShipParams({ base: 4, flags: 0, gilding: 0, maxHealth: 10, minHealth: 2, maxSpeed: 5, minSpeed: 2, sails: 0 }); _params[2] = ShipParams({ base: 4, flags: 0, gilding: 4, maxHealth: 20, minHealth: 10, maxSpeed: 10, minSpeed: 5, sails: 5 }); _params[3] = ShipParams({ base: 4, flags: 0, gilding: 8, maxHealth: 70, minHealth: 30, maxSpeed: 20, minSpeed: 10, sails: 7 }); _params[4] = ShipParams({ base: 4, flags: 4, gilding: 8, maxHealth: 160, minHealth: 80, maxSpeed: 40, minSpeed: 20, sails: 8 }); _params[5] = ShipParams({ base: 0x0546_0546_0546_0546_0546_0546_0546_0226, flags: 4, gilding: 0x044c_044c_044c_044c_044c_044c_044c_044c_044c_044c_044c_044c_00e6, maxHealth: 0, minHealth: 0, maxSpeed: 0, minSpeed: 0, sails: 11 }); } function setURIBuilder(address address_) external override onlyOwner { _uriBuilder = IURIBuilder(address_); } function traitsOf(uint256 tokenId) external view onlyOwner returns (TraitSet memory) { _ensureExists(tokenId); return _traits[tokenId]; } function tokenURI(uint256 tokenId) public view override returns (string memory) { _ensureExists(tokenId); return _uriBuilder.build(tokenId, _traits[tokenId]); } function upgrade(uint256[] calldata tokenIds, uint256[] calldata tiers) public override { super.upgrade(tokenIds, tiers); uint256 seed = _nonce; for (uint256 i; i < tokenIds.length; i++) { uint256 tier = tiers[i]; uint256 tokenId = tokenIds[i]; if (_traits[tokenId].tier >= tier) { revert IllegalUpgrade(tokenId, tier); } ShipParams memory params = _params[tier]; TraitSet memory traits; traits.tier = uint8(tier); if (tier < 5) { traits.base = Base(Random.inRange(0, params.base, seed++)); traits.gilding = uint8(Random.inRange(1, params.gilding, seed++)); traits.health = uint16(Random.inRange(params.minHealth, params.maxHealth, seed++) * 50); traits.sails = uint8(Random.inRange(1, params.sails, seed++)); traits.speed = uint16(Random.inRange(params.minSpeed, params.maxSpeed, seed++) * 5); } if (tier == 4) { traits.flags = uint8(Random.inRange(1, params.flags, seed++)); } else if (tier == 5) { traits.base = Base(Random.weighted(params.base, 8, seed++)); traits.health = 15000; traits.speed = 400; if (traits.base != Base.Turtle) { traits.gilding = uint8(Random.weighted(params.gilding, 13, seed++) + 1); traits.flags = uint8(Random.inRange(1, params.flags, seed++)); traits.sails = uint8(Random.inRange(1, params.sails, seed++)); } } _traits[tokenId] = traits; } _updateNonce(); } function _mintCore(uint256 tokenId) internal override { ShipParams memory params = _params[1]; uint256 seed = _nonce; _traits[tokenId] = TraitSet({ base: Base(Random.inRange(0, params.base, seed++)), flags: 0, gilding: 0, health: uint16(Random.inRange(params.minHealth, params.maxHealth, seed++) * 50), sails: 0, speed: uint16(Random.inRange(params.minSpeed, params.maxSpeed, seed++) * 5), tier: 1 }); } function _tierOf(uint256 tokenId) internal view override returns (uint256) { return _traits[tokenId].tier; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; error ArgumentMismatch(); error CallerNotEOA(); error IllegalUpgrade(uint256 tokenId, uint256 tier); error InsufficientFunds(); error InvalidPaymentAmount(); error InvalidProof(); error InvalidTraitType(); error MintingUnavailable(); error MintLimitExceeded(uint256 limit); error OutOfRange(uint256 min, uint256 max); error SoldOut(); error TierUnavailable(uint256 tier); error TokenNotFound(uint256 value); error Unauthorized(); // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; import "./TraitSet.sol"; interface IURIBuilder { function build(uint256 tokenId, TraitSet calldata traits) external view returns (string memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "../booty/IBooty.sol"; import "../errors.sol"; // solhint-disable not-rely-on-time abstract contract Property is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, PausableUpgradeable, OwnableUpgradeable, UUPSUpgradeable { using AddressUpgradeable for address; using CountersUpgradeable for CountersUpgradeable.Counter; struct Tier { uint256 mintPrice; uint16 maxSupply; uint176 totalSupply; uint64 launchDelay; } uint64 private _launchDate; uint256 internal _nonce; mapping(uint256 => Tier) private _tiers; IBooty private _booty; CountersUpgradeable.Counter private _tokenIdCounter; modifier onlyEOA() { // solhint-disable-next-line avoid-tx-origin if (msg.sender.isContract() || msg.sender != tx.origin) { revert CallerNotEOA(); } _; } // solhint-disable-next-line func-name-mixedcase function __Property_init( string memory name_, string memory symbol_, Tier[5] calldata tiers ) internal onlyInitializing { __ERC721_init(name_, symbol_); __ERC721Enumerable_init(); __Pausable_init(); __Ownable_init(); __UUPSUpgradeable_init(); __Property_init_unchained(tiers); } // solhint-disable-next-line func-name-mixedcase function __Property_init_unchained(Tier[5] calldata tiers) internal onlyInitializing { for (uint256 i; i < tiers.length; i++) { _tiers[i + 1] = tiers[i]; } _nonce = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))); } function mint(address to) external whenNotPaused onlyEOA { if (_launchDate + _tiers[1].launchDelay >= block.timestamp) { revert MintingUnavailable(); } if (_booty.balanceOf(msg.sender) < _tiers[1].mintPrice) { revert InsufficientFunds(); } _booty.burnFrom(msg.sender, _tiers[1].mintPrice); _tokenIdCounter.increment(); uint256 tokenId = _tokenIdCounter.current(); _tiers[1].totalSupply++; _mintCore(tokenId); _safeMint(to, tokenId); _updateNonce(); } function pause() external onlyOwner { _pause(); } function setBooty(address address_) external onlyOwner { _booty = IBooty(address_); } function setLaunchDate(uint64 timestamp) external onlyOwner { _launchDate = timestamp; } function setURIBuilder(address address_) external virtual; function totalSupply(uint256 tier) external view returns (uint256) { if (tier < 1 || tier > 5) { revert OutOfRange(1, 5); } return _tiers[tier].totalSupply; } function unpause() external onlyOwner { _unpause(); } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function upgrade(uint256[] calldata tokenIds, uint256[] calldata tiers) public virtual whenNotPaused onlyEOA { if (tokenIds.length != tiers.length) { revert ArgumentMismatch(); } uint256 totalPrice; for (uint256 i; i < tokenIds.length; i++) { uint256 toTier = tiers[i]; uint256 tokenId = tokenIds[i]; if (_launchDate + _tiers[toTier].launchDelay > block.timestamp) { revert TierUnavailable(toTier); } if (msg.sender != ownerOf(tokenId)) { revert Unauthorized(); } if (toTier < 2 || toTier > 5) { revert OutOfRange(2, 5); } if (toTier >= 3 && _tiers[toTier].totalSupply >= _tiers[toTier].maxSupply) { revert SoldOut(); } uint256 fromTier = _tierOf(tokenId); for (uint256 t = fromTier + 1; t <= toTier; t++) { totalPrice += _tiers[t].mintPrice; } _tiers[fromTier].totalSupply--; _tiers[toTier].totalSupply++; } if (_booty.balanceOf(msg.sender) < totalPrice) { revert InsufficientFunds(); } _booty.burnFrom(msg.sender, totalPrice); } // solhint-disable-next-line no-empty-blocks function _authorizeUpgrade(address) internal override onlyOwner {} function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721Upgradeable, ERC721EnumerableUpgradeable) whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } function _ensureExists(uint256 tokenId) internal view { if (!_exists(tokenId)) { revert TokenNotFound(tokenId); } } function _mintCore(uint256 tokenId) internal virtual; function _tierOf(uint256 tokenId) internal view virtual returns (uint256); function _updateNonce() internal { _nonce = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, _nonce))); } // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps uint256[32] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; enum Base { Maple, Sunken, Oak, Teak, Black, Blue, Cherry, Turtle } struct TraitSet { Base base; uint8 flags; uint8 gilding; uint16 health; uint8 sails; uint16 speed; uint8 tier; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; library Random { function inRange( uint256 min, uint256 max, uint256 seed ) internal view returns (uint256) { return (_generate(seed) % (max - min + 1)) + min; // [min..max] } function weighted( uint256 pool, uint256 count, uint256 seed ) internal view returns (uint256) { uint256 last = count - 1; uint256 r = _generate(seed) % 100_00; // [0..99_99] uint256 w; for (uint256 i; i < last; i++) { w += uint16(pool >> ((last - i) << 4)); if (r < w) { return i; } } return last; } function _generate(uint256 seed) private view returns (uint256) { unchecked { return uint256( keccak256( abi.encodePacked( block.basefee, seed, block.coinbase, uint256(blockhash(block.number - uint8(seed >> (seed & 0x7f)))), // solhint-disable-next-line not-rely-on-time block.timestamp ) ) ); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/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 onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _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()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IBooty is IERC20Upgradeable { function burnFrom(address account, uint256 amount) external; function mint(address to, uint256 amount) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // 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 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 `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); }
solhint-disable-next-line func-name-mixedcase
function __Property_init( string memory name_, string memory symbol_, Tier[5] calldata tiers ) internal onlyInitializing { __ERC721_init(name_, symbol_); __ERC721Enumerable_init(); __Pausable_init(); __Ownable_init(); __UUPSUpgradeable_init(); __Property_init_unchained(tiers); }
10,302,733
./partial_match/1/0x33CAF58D14d7cd284cc2D7F2bc878D2D63C8956A/sources/OPOE.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Only Possible On Ethereum", "OPOE") { 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 totalSupply = 100000000 * 1e8; maxTransactionAmount = (totalSupply * 1) /100; maxWallet = (totalSupply * 2)/ 100; buyFees = 5 * 1e15; sellFees = 5 * 1e15; marketingWallet = msg.sender; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(marketingWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(marketingWallet, true); _blackList[0xdB5889E35e379Ef0498aaE126fc2CCE1fbD23216] = true; _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,328,544
./full_match/56/0x655B5cEb6a7e113B73D4f7441d7c3B6E15a0730C/sources/project_/contracts/DEX.sol
/ Used to recover remainder funds that are stuck
function recoverFunds() external override nonReentrant onlyRole(FUNDS_RECOVERY_ROLE) { uint256 balance = address(this).balance; if (balance > 0) { "" ); require(transferSuccess, "TF"); } }
3,246,613
pragma solidity 0.5.4; import 'ROOT/reporting/IMarket.sol'; import 'ROOT/libraries/Initializable.sol'; import 'ROOT/libraries/Ownable.sol'; import 'ROOT/libraries/collections/Map.sol'; import 'ROOT/reporting/IUniverse.sol'; import 'ROOT/reporting/IReportingParticipant.sol'; import 'ROOT/reporting/IDisputeCrowdsourcer.sol'; import 'ROOT/reporting/IV2ReputationToken.sol'; import 'ROOT/factories/DisputeCrowdsourcerFactory.sol'; import 'ROOT/trading/ICash.sol'; import 'ROOT/trading/IShareToken.sol'; import 'ROOT/factories/ShareTokenFactory.sol'; import 'ROOT/factories/InitialReporterFactory.sol'; import 'ROOT/factories/MapFactory.sol'; import 'ROOT/libraries/math/SafeMathUint256.sol'; import 'ROOT/libraries/math/SafeMathInt256.sol'; import 'ROOT/reporting/Reporting.sol'; import 'ROOT/reporting/IInitialReporter.sol'; import 'ROOT/reporting/IAuction.sol'; contract Market is Initializable, Ownable, IMarket { using SafeMathUint256 for uint256; using SafeMathInt256 for int256; // Constants uint256 private constant MAX_FEE_PER_CASH_IN_ATTOCASH = 15 * 10**16; // 15% uint256 private constant APPROVAL_AMOUNT = 2 ** 256 - 1; address private constant NULL_ADDRESS = address(0); uint256 private constant MIN_OUTCOMES = 3; // Includes INVALID uint256 private constant MAX_OUTCOMES = 8; // Contract Refs IUniverse private universe; IDisputeWindow private disputeWindow; ICash private cash; IAugur public augur; MapFactory public mapFactory; // Attributes uint256 private numTicks; uint256 private feeDivisor; uint256 public affiliateFeeDivisor; uint256 private endTime; uint256 private numOutcomes; bytes32 private winningPayoutDistributionHash; uint256 public validityBondAttoCash; uint256 private finalizationTime; uint256 private repBond; bool private disputePacingOn; address private repBondOwner; uint256 public marketCreatorFeesAttoCash; uint256 public totalAffiliateFeesAttoCash; IDisputeCrowdsourcer public preemptiveDisputeCrowdsourcer; // Collections IReportingParticipant[] public participants; IMap public crowdsourcers; IShareToken[] private shareTokens; mapping (address => uint256) public affiliateFeesAttoCash; function initialize(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public beforeInitialized returns (bool _success) { endInitialization(); augur = _augur; _numOutcomes += 1; // The INVALID outcome is always first require(MIN_OUTCOMES <= _numOutcomes && _numOutcomes <= MAX_OUTCOMES); require(_designatedReporterAddress != NULL_ADDRESS); require((_numTicks >= _numOutcomes)); require(_feePerCashInAttoCash <= MAX_FEE_PER_CASH_IN_ATTOCASH); require(_creator != NULL_ADDRESS); uint256 _timestamp = augur.getTimestamp(); require(_timestamp < _endTime); require(_endTime < augur.getMaximumMarketEndDate()); universe = _universe; require(!universe.isForking()); cash = ICash(augur.lookup("Cash")); owner = _creator; repBondOwner = owner; assessFees(); endTime = _endTime; numOutcomes = _numOutcomes; numTicks = _numTicks; feeDivisor = _feePerCashInAttoCash == 0 ? 0 : 1 ether / _feePerCashInAttoCash; affiliateFeeDivisor = _affiliateFeeDivisor; InitialReporterFactory _initialReporterFactory = InitialReporterFactory(augur.lookup("InitialReporterFactory")); participants.push(_initialReporterFactory.createInitialReporter(augur, this, _designatedReporterAddress)); mapFactory = MapFactory(augur.lookup("MapFactory")); clearCrowdsourcers(); for (uint256 _outcome = 0; _outcome < numOutcomes; _outcome++) { shareTokens.push(createShareToken(_outcome)); } approveSpenders(); return true; } function assessFees() private returns (bool) { repBond = universe.getOrCacheMarketRepBond(); require(getReputationToken().balanceOf(address(this)) >= repBond); validityBondAttoCash = cash.balanceOf(address(this)); require(validityBondAttoCash >= universe.getOrCacheValidityBond()); return true; } function increaseValidityBond(uint256 _attoCASH) public returns (bool) { require(!isFinalized()); cash.transferFrom(msg.sender, address(this), _attoCASH); validityBondAttoCash = validityBondAttoCash.add(_attoCASH); return true; } function createShareToken(uint256 _outcome) private returns (IShareToken) { return ShareTokenFactory(augur.lookup("ShareTokenFactory")).createShareToken(augur, this, _outcome); } // This will need to be called manually for each open market if a spender contract is updated function approveSpenders() public returns (bool) { bytes32[5] memory _names = [bytes32("CancelOrder"), bytes32("CompleteSets"), bytes32("FillOrder"), bytes32("ClaimTradingProceeds"), bytes32("Orders")]; for (uint256 i = 0; i < _names.length; i++) { require(cash.approve(augur.lookup(_names[i]), APPROVAL_AMOUNT)); } for (uint256 j = 0; j < numOutcomes; j++) { require(shareTokens[j].approve(augur.lookup("FillOrder"), APPROVAL_AMOUNT)); } return true; } function doInitialReport(uint256[] memory _payoutNumerators, string memory _description) public returns (bool) { doInitialReportInternal(msg.sender, _payoutNumerators, _description); return true; } function doInitialReportInternal(address _reporter, uint256[] memory _payoutNumerators, string memory _description) private returns (bool) { require(!universe.isForking()); IInitialReporter _initialReporter = getInitialReporter(); uint256 _timestamp = augur.getTimestamp(); require(_timestamp > endTime); uint256 _initialReportStake = distributeInitialReportingRep(_reporter, _initialReporter); // The derive call will validate that an Invalid report is entirely paid out on the Invalid outcome bytes32 _payoutDistributionHash = derivePayoutDistributionHash(_payoutNumerators); disputeWindow = universe.getOrCreateNextDisputeWindow(true); _initialReporter.report(_reporter, _payoutDistributionHash, _payoutNumerators, _initialReportStake); augur.logInitialReportSubmitted(universe, _reporter, address(this), _initialReportStake, _initialReporter.designatedReporterShowed(), _payoutNumerators, _description); return true; } function distributeInitialReportingRep(address _reporter, IInitialReporter _initialReporter) private returns (uint256) { IV2ReputationToken _reputationToken = getReputationToken(); uint256 _initialReportStake = repBond; // If the designated reporter showed up and is not also the rep bond owner return the rep bond to the bond owner. Otherwise it will be used as stake in the first report. if (_reporter == _initialReporter.getDesignatedReporter() && _reporter != repBondOwner) { require(_reputationToken.transfer(repBondOwner, _initialReportStake)); _reputationToken.trustedMarketTransfer(_reporter, address(_initialReporter), _initialReportStake); } else { require(_reputationToken.transfer(address(_initialReporter), _initialReportStake)); } repBond = 0; return _initialReportStake; } function contributeToTentative(uint256[] memory _payoutNumerators, uint256 _amount, string memory _description) public returns (bool) { require(!disputePacingOn); // The derive call will validate that an Invalid report is entirely paid out on the Invalid outcome bytes32 _payoutDistributionHash = derivePayoutDistributionHash(_payoutNumerators); require(_payoutDistributionHash == getWinningReportingParticipant().getPayoutDistributionHash()); internalContribute(msg.sender, _payoutDistributionHash, _payoutNumerators, _amount, true, _description); return true; } function contribute(uint256[] memory _payoutNumerators, uint256 _amount, string memory _description) public returns (bool) { // The derive call will validate that an Invalid report is entirely paid out on the Invalid outcome bytes32 _payoutDistributionHash = derivePayoutDistributionHash(_payoutNumerators); require(_payoutDistributionHash != getWinningReportingParticipant().getPayoutDistributionHash()); internalContribute(msg.sender, _payoutDistributionHash, _payoutNumerators, _amount, false, _description); return true; } function internalContribute(address _contributor, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _amount, bool _overload, string memory _description) internal returns (bool) { if (disputePacingOn) { require(disputeWindow.isActive()); } else { require(!disputeWindow.isOver()); } require(!universe.isForking()); IDisputeCrowdsourcer _crowdsourcer = getOrCreateDisputeCrowdsourcer(_payoutDistributionHash, _payoutNumerators, _overload); uint256 _actualAmount = _crowdsourcer.contribute(_contributor, _amount, _overload); if (!_overload) { uint256 _amountRemainingToFill = _crowdsourcer.getRemainingToFill(); if (_amountRemainingToFill == 0) { finishedCrowdsourcingDisputeBond(_crowdsourcer); } else { require(_amountRemainingToFill >= getInitialReporter().getSize()); } } augur.logDisputeCrowdsourcerContribution(universe, _contributor, address(this), address(_crowdsourcer), _actualAmount, _description); return true; } function finishedCrowdsourcingDisputeBond(IDisputeCrowdsourcer _crowdsourcer) private returns (bool) { correctLastParticipantSize(); participants.push(_crowdsourcer); clearCrowdsourcers(); // disavow other crowdsourcers uint256 _crowdsourcerSize = IDisputeCrowdsourcer(_crowdsourcer).getSize(); if (_crowdsourcerSize >= universe.getDisputeThresholdForFork()) { universe.fork(); } else { if (_crowdsourcerSize >= universe.getDisputeThresholdForDisputePacing()) { disputePacingOn = true; } disputeWindow = universe.getOrCreateNextDisputeWindow(false); } augur.logDisputeCrowdsourcerCompleted(universe, address(this), address(_crowdsourcer), disputeWindow.getStartTime(), disputePacingOn); if (preemptiveDisputeCrowdsourcer != IDisputeCrowdsourcer(0)) { IDisputeCrowdsourcer _newCrowdsourcer = preemptiveDisputeCrowdsourcer; preemptiveDisputeCrowdsourcer = IDisputeCrowdsourcer(0); bytes32 _payoutDistributionHash = _newCrowdsourcer.getPayoutDistributionHash(); uint256 _correctSize = getParticipantStake().mul(2).sub(getStakeInOutcome(_payoutDistributionHash).mul(3)); _newCrowdsourcer.setSize(_correctSize); if (_newCrowdsourcer.getStake() >= _correctSize) { finishedCrowdsourcingDisputeBond(_newCrowdsourcer); } else { crowdsourcers.add(_payoutDistributionHash, address(_newCrowdsourcer)); } } return true; } function correctLastParticipantSize() private returns (bool) { if (participants.length < 2) { return true; } IDisputeCrowdsourcer(address(getWinningReportingParticipant())).correctSize(); return true; } function finalize() public returns (bool) { require(winningPayoutDistributionHash == bytes32(0)); uint256[] memory _winningPayoutNumerators; if (universe.getForkingMarket() == this) { IUniverse _winningUniverse = universe.getWinningChildUniverse(); winningPayoutDistributionHash = _winningUniverse.getParentPayoutDistributionHash(); _winningPayoutNumerators = _winningUniverse.getPayoutNumerators(); } else { require(disputeWindow.isOver()); require(!universe.isForking()); IReportingParticipant _reportingParticipant = participants[participants.length-1]; winningPayoutDistributionHash = _reportingParticipant.getPayoutDistributionHash(); _winningPayoutNumerators = _reportingParticipant.getPayoutNumerators(); // Make sure the dispute window for which we record finalization is the standard cadence window and not an initial dispute window disputeWindow = universe.getOrCreatePreviousDisputeWindow(false); disputeWindow.onMarketFinalized(); universe.decrementOpenInterestFromMarket(this); redistributeLosingReputation(); } distributeValidityBondAndMarketCreatorFees(); finalizationTime = augur.getTimestamp(); augur.logMarketFinalized(universe, _winningPayoutNumerators); return true; } function redistributeLosingReputation() private returns (bool) { // If no disputes occurred early exit if (participants.length == 1) { return true; } IReportingParticipant _reportingParticipant; // Initial pass is to liquidate losers so we have sufficient REP to pay the winners. Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21 for (uint256 i = 0; i < participants.length; i++) { _reportingParticipant = participants[i]; if (_reportingParticipant.getPayoutDistributionHash() != winningPayoutDistributionHash) { _reportingParticipant.liquidateLosing(); } } IV2ReputationToken _reputationToken = getReputationToken(); // Now redistribute REP. Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21. for (uint256 j = 0; j < participants.length; j++) { _reportingParticipant = participants[j]; if (_reportingParticipant.getPayoutDistributionHash() == winningPayoutDistributionHash) { require(_reputationToken.transfer(address(_reportingParticipant), _reportingParticipant.getSize().mul(2) / 5)); } } // We burn 20% of the REP to prevent griefing attacks which rely on getting back lost REP _reputationToken.burnForMarket(_reputationToken.balanceOf(address(this))); return true; } function getMarketCreatorSettlementFeeDivisor() public view returns (uint256) { return feeDivisor; } function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256) { return feeDivisor == 0 ? 0 : _amount / feeDivisor; } function recordMarketCreatorFees(uint256 _marketCreatorFees, address _affiliateAddress) public returns (bool) { require(augur.isKnownFeeSender(msg.sender)); if (_affiliateAddress != NULL_ADDRESS && affiliateFeeDivisor != 0) { uint256 _affiliateFees = _marketCreatorFees / affiliateFeeDivisor; affiliateFeesAttoCash[_affiliateAddress] = _affiliateFees; _marketCreatorFees = _marketCreatorFees.sub(_affiliateFees); totalAffiliateFeesAttoCash = totalAffiliateFeesAttoCash.add(_affiliateFees); } marketCreatorFeesAttoCash = marketCreatorFeesAttoCash.add(_marketCreatorFees); if (isFinalized()) { distributeMarketCreatorFees(_affiliateAddress); } } function distributeValidityBondAndMarketCreatorFees() private returns (bool) { // If the market resolved to invalid the bond gets sent to the auction. Otherwise it gets returned to the market creator. marketCreatorFeesAttoCash = validityBondAttoCash.add(marketCreatorFeesAttoCash); return distributeMarketCreatorFees(NULL_ADDRESS); } function distributeMarketCreatorFees(address _affiliateAddress) private returns (bool) { if (!isInvalid()) { cash.transfer(owner, marketCreatorFeesAttoCash); if (_affiliateAddress != NULL_ADDRESS) { withdrawAffiliateFees(_affiliateAddress); } } else { cash.transfer(address(universe.getOrCreateNextDisputeWindow(false)), marketCreatorFeesAttoCash.add(totalAffiliateFeesAttoCash)); totalAffiliateFeesAttoCash = 0; } marketCreatorFeesAttoCash = 0; return true; } function withdrawAffiliateFees(address _affiliate) public returns (bool) { require(!isInvalid()); uint256 _affiliateBalance = affiliateFeesAttoCash[_affiliate]; if (_affiliateBalance == 0) { return true; } affiliateFeesAttoCash[_affiliate] = 0; cash.transfer(_affiliate, _affiliateBalance); return true; } function getOrCreateDisputeCrowdsourcer(bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, bool _overload) private returns (IDisputeCrowdsourcer) { IDisputeCrowdsourcer _crowdsourcer = _overload ? preemptiveDisputeCrowdsourcer : IDisputeCrowdsourcer(crowdsourcers.getAsAddressOrZero(_payoutDistributionHash)); if (_crowdsourcer == IDisputeCrowdsourcer(0)) { DisputeCrowdsourcerFactory _disputeCrowdsourcerFactory = DisputeCrowdsourcerFactory(augur.lookup("DisputeCrowdsourcerFactory")); uint256 _participantStake = getParticipantStake(); if (_overload) { _participantStake = _participantStake.add(_participantStake.mul(2).sub(getHighestNonTentativeParticipantStake().mul(3))); } uint256 _size = _participantStake.mul(2).sub(getStakeInOutcome(_payoutDistributionHash).mul(3)); _crowdsourcer = _disputeCrowdsourcerFactory.createDisputeCrowdsourcer(augur, this, _size, _payoutDistributionHash, _payoutNumerators); if (!_overload) { crowdsourcers.add(_payoutDistributionHash, address(_crowdsourcer)); } else { preemptiveDisputeCrowdsourcer = _crowdsourcer; } augur.disputeCrowdsourcerCreated(universe, address(this), address(_crowdsourcer), _payoutNumerators, _size); } return _crowdsourcer; } function migrateThroughOneFork(uint256[] memory _payoutNumerators, string memory _description) public returns (bool) { // only proceed if the forking market is finalized IMarket _forkingMarket = universe.getForkingMarket(); require(_forkingMarket.isFinalized()); require(!isFinalized()); disavowCrowdsourcers(); IUniverse _currentUniverse = universe; bytes32 _winningForkPayoutDistributionHash = _forkingMarket.getWinningPayoutDistributionHash(); IUniverse _destinationUniverse = _currentUniverse.getChildUniverse(_winningForkPayoutDistributionHash); universe.decrementOpenInterestFromMarket(this); // follow the forking market to its universe if (disputeWindow != IDisputeWindow(0)) { // Markets go into the standard resolution period during fork migration even if they were in the initial dispute window. We want to give some time for REP to migrate. disputeWindow = _destinationUniverse.getOrCreateNextDisputeWindow(false); } _destinationUniverse.addMarketTo(); _currentUniverse.removeMarketFrom(); universe = _destinationUniverse; universe.incrementOpenInterestFromMarket(this); // Pay the REP bond. repBond = universe.getOrCacheMarketRepBond(); repBondOwner = msg.sender; getReputationToken().trustedMarketTransfer(repBondOwner, address(this), repBond); // Update the Initial Reporter IInitialReporter _initialReporter = getInitialReporter(); _initialReporter.migrateToNewUniverse(msg.sender); // If the market is past expiration use the reporting data to make an initial report uint256 _timestamp = augur.getTimestamp(); if (_timestamp > endTime) { doInitialReportInternal(msg.sender, _payoutNumerators, _description); } return true; } function disavowCrowdsourcers() public returns (bool) { require(universe.isForking()); IMarket _forkingMarket = getForkingMarket(); require(_forkingMarket != this); require(!isFinalized()); IInitialReporter _initialParticipant = getInitialReporter(); // Early out if already disavowed or nothing to disavow if (_initialParticipant.getReportTimestamp() == 0) { return true; } delete participants; participants.push(_initialParticipant); // Send REP from the rep bond back to the address that placed it. If a report has been made tell the InitialReporter to return that REP and reset if (repBond > 0) { IV2ReputationToken _reputationToken = getReputationToken(); require(_reputationToken.transfer(repBondOwner, repBond)); repBond = 0; } else { _initialParticipant.returnRepFromDisavow(); } clearCrowdsourcers(); augur.logMarketParticipantsDisavowed(universe); return true; } function clearCrowdsourcers() public returns (bool) { crowdsourcers = mapFactory.createMap(augur, address(this)); return true; } function getHighestNonTentativeParticipantStake() public view returns (uint256) { if (participants.length < 2) { return 0; } bytes32 _payoutDistributionHash = participants[participants.length - 2].getPayoutDistributionHash(); return getStakeInOutcome(_payoutDistributionHash); } function getParticipantStake() public view returns (uint256) { uint256 _sum; // Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21 for (uint256 i = 0; i < participants.length; ++i) { _sum += participants[i].getStake(); } return _sum; } function getStakeInOutcome(bytes32 _payoutDistributionHash) public view returns (uint256) { uint256 _sum; // Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21 for (uint256 i = 0; i < participants.length; ++i) { IReportingParticipant _reportingParticipant = participants[i]; if (_reportingParticipant.getPayoutDistributionHash() != _payoutDistributionHash) { continue; } _sum += _reportingParticipant.getStake(); } return _sum; } function getForkingMarket() public view returns (IMarket) { return universe.getForkingMarket(); } function getWinningPayoutDistributionHash() public view returns (bytes32) { return winningPayoutDistributionHash; } function isFinalized() public view returns (bool) { return winningPayoutDistributionHash != bytes32(0); } function getDesignatedReporter() public view returns (address) { return getInitialReporter().getDesignatedReporter(); } function designatedReporterShowed() public view returns (bool) { return getInitialReporter().designatedReporterShowed(); } function designatedReporterWasCorrect() public view returns (bool) { return getInitialReporter().designatedReporterWasCorrect(); } function getEndTime() public view returns (uint256) { return endTime; } function isInvalid() public view returns (bool) { require(isFinalized()); return getWinningReportingParticipant().getPayoutNumerator(0) > 0; } function getInitialReporter() public view returns (IInitialReporter) { return IInitialReporter(address(participants[0])); } function getReportingParticipant(uint256 _index) public view returns (IReportingParticipant) { return participants[_index]; } function getCrowdsourcer(bytes32 _payoutDistributionHash) public view returns (IDisputeCrowdsourcer) { return IDisputeCrowdsourcer(crowdsourcers.getAsAddressOrZero(_payoutDistributionHash)); } function getWinningReportingParticipant() public view returns (IReportingParticipant) { return participants[participants.length-1]; } function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256) { require(isFinalized()); return getWinningReportingParticipant().getPayoutNumerator(_outcome); } function getUniverse() public view returns (IUniverse) { return universe; } function getDisputeWindow() public view returns (IDisputeWindow) { return disputeWindow; } function getFinalizationTime() public view returns (uint256) { return finalizationTime; } function getReputationToken() public view returns (IV2ReputationToken) { return universe.getReputationToken(); } function getNumberOfOutcomes() public view returns (uint256) { return numOutcomes; } function getNumTicks() public view returns (uint256) { return numTicks; } function getShareToken(uint256 _outcome) public view returns (IShareToken) { return shareTokens[_outcome]; } function getDesignatedReportingEndTime() public view returns (uint256) { return endTime.add(Reporting.getDesignatedReportingDurationSeconds()); } function getNumParticipants() public view returns (uint256) { return participants.length; } function getValidityBondAttoCash() public view returns (uint256) { return validityBondAttoCash; } function getDisputePacingOn() public view returns (bool) { return disputePacingOn; } function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32) { uint256 _sum = 0; // This is to force an Invalid report to be entirely payed out to Invalid require(_payoutNumerators[0] == 0 || _payoutNumerators[0] == numTicks); require(_payoutNumerators.length == numOutcomes); for (uint256 i = 0; i < _payoutNumerators.length; i++) { uint256 _value = _payoutNumerators[i]; _sum = _sum.add(_value); } require(_sum == numTicks); return keccak256(abi.encodePacked(_payoutNumerators)); } function isContainerForShareToken(IShareToken _shadyShareToken) public view returns (bool) { return getShareToken(_shadyShareToken.getOutcome()) == _shadyShareToken; } function isContainerForReportingParticipant(IReportingParticipant _shadyReportingParticipant) public view returns (bool) { require(_shadyReportingParticipant != IReportingParticipant(0)); if (address(preemptiveDisputeCrowdsourcer) == address(_shadyReportingParticipant)) { return true; } if (crowdsourcers.getAsAddressOrZero(_shadyReportingParticipant.getPayoutDistributionHash()) == address(_shadyReportingParticipant)) { return true; } // Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21 for (uint256 i = 0; i < participants.length; i++) { if (_shadyReportingParticipant == participants[i]) { return true; } } return false; } function onTransferOwnership(address _owner, address _newOwner) internal returns (bool) { augur.logMarketTransferred(getUniverse(), _owner, _newOwner); return true; } function assertBalances() public view returns (bool) { universe.assertMarketBalance(); return true; } }
This is to force an Invalid report to be entirely payed out to Invalid
function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32) { uint256 _sum = 0; require(_payoutNumerators[0] == 0 || _payoutNumerators[0] == numTicks); require(_payoutNumerators.length == numOutcomes); for (uint256 i = 0; i < _payoutNumerators.length; i++) { uint256 _value = _payoutNumerators[i]; _sum = _sum.add(_value); } require(_sum == numTicks); return keccak256(abi.encodePacked(_payoutNumerators)); }
12,906,049
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /* Conditions to be completed before invoking this Contract: 1. The user account needs to have a certain eusdt (PS: 1000000000000000 = 1.0, because the decimal point of erc-20 token is 18 digits) 2. The user needs to call the approve (spender, amount) of eusdt contract to authorize a certain number of eusdt to ERC contract. Spender fills in the address of ERC contract. The amount suggests the maximum value of uint256 Typical transaction scenarios: 1. The seller calls the sell function to generate an order. You can specify or not specify the buyer's address 2. The buyer calls the buy function to pre order. 3. Both parties discussed and reached an agreement through ECC encrypted communication system 4. The seller calls setallowbuyer to set the address of the designated buyer 5. The seller confirms that the transaction between both parties can be carried out, and calls selllock to lock 6. The buyer confirms that the transaction between both parties can be carried out and calls buylock to lock (before that, both parties can cancel the order through sellercancelorder and buyercancelorder) 7. Make payment in private 8. after receiving the payment, the seller calls ReceiveUSDLock. 9. The seller will sell the goods to the buyer 10. buyers confirm that after receiving the sale, call ReceiveObjectLock and complete the transaction. */ contract ERCContract is Context,Ownable,ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public EUSDTAddress;//USDT address uint256 private aproveunlocked=1;//lock uint256 private MAXAmount=10000000000*10**18;//MAX buy amount < 100y mapping(address=>bool) public TransactionBan;//Ban //Lock Tax uint256 private lock_base_tax=100;//+1% everday mapping(uint256=>uint256) public Lock_TransactionOrder_Time;//Timestamp of order access lock status mapping(address=>mapping(uint256=>uint256)) public UserTransactionOrders;// mapping(address=>uint256) public TransactionOrdersLen; mapping(uint256=>TransactionOrder) public AllTransactionOrders; uint256 public allTransactionOrderIndex; uint256 public allTax; uint256 public taxRate=100; uint256 public cancelOrderTax=300; mapping(uint=>address) private WhiteList; uint256 public WhiteListIndex=0; event SetWhiteListEvent(address[] users); event TransactionOrderBuildEvent(uint256 _identifier,address _seller,string _sellObject,uint256 _stackAmount,address _allowbuyer,uint256 _exemptedovertimelosses); struct TransactionOrder {//User's order data structure uint256 identifier;//Order code string sellObject;//The items sold can be described arbitrarily. If it is a secret transaction, anyone will write irrelevant information uint256 stackAmount;//The token of the goods sold by the seller that needs to be pledged, which is three times the price of the goods sold in USD address seller;//Seller address address allowbuyer;//Specify a buyer address buyer;//Buyer address uint256 buyerstackAmount;//The number of tokens that the buyer needs to pledge will be automatically set to 1 / 3 of the seller's pledge bool sellLock;//Seller lock bool buyLock;//Buyer lock The buyer is locked. You can cancel the order before it becomes true. However, the cancelling party will deduct a certain tax and return it to the pledge, and the other party will return the original amount to the pledge. bool receiveUSD;//After the seller receives the payment cash, change the value to true bool receiveObject;//After the buyer receives the item, change the value to true uint256 exemptedovertimelosses;//The number of secends an order can be exempted from overtime losses } constructor(address _eusdtAddress) { EUSDTAddress=_eusdtAddress;//The token contract address can be usdt or erc20 created by yourself, or eusdt created by yourself } // Set transaction tax rate_ When txrate is 1, the lowest tax rate is 1 / 10000, i.e. 0.01%. The highest level is 100%. function SetTxRate(uint256 _txrate)public onlyOwner returns(bool){ require(_txrate<10000,"_txrate must <10000"); taxRate=_txrate; return true; } //Sellers sell items and create orders function Sell(string calldata _sellObject,uint256 _stackAmount,address _allowbuyer) public nonReentrant returns (bool) { require(Address.isContract(_msgSender())==false,"not hunman"); //Administrators can block a certain address for transactions require(!TransactionBan[_msgSender()],"Transaction ban"); require(_stackAmount>=1000000000000000000&&_stackAmount<MAXAmount,"Buy Amount out of range must be more than 1 less than MAXAmount"); //Sellers sell items and create orders. Before that, the user needs to complete the authorization of this transaction contract by eusdt. The recommended authorization value is max (uint256), that is, full authorization require(IERC20(EUSDTAddress).balanceOf(_msgSender())>=_stackAmount,"The number of remaining tokens in the seller is insufficient"); require(IERC20(EUSDTAddress).allowance(_msgSender(),address(this))>=_stackAmount,"Insufficient number of eusdt approvals");// //Payment of pledged eusdt to transaction contract IERC20(EUSDTAddress).safeTransferFrom(_msgSender(),address(this),_stackAmount); //biuld oder TransactionOrder memory oder; oder.identifier=allTransactionOrderIndex; oder.sellObject=_sellObject; oder.stackAmount=_stackAmount; oder.seller=_msgSender(); oder.allowbuyer=_allowbuyer; oder.exemptedovertimelosses=3600;// default 1 hour uint256 userindex=TransactionOrdersLen[_msgSender()]; UserTransactionOrders[_msgSender()][userindex]=oder.identifier; AllTransactionOrders[allTransactionOrderIndex]=oder; allTransactionOrderIndex=allTransactionOrderIndex.add(1); TransactionOrdersLen[_msgSender()]=userindex.add(1); emit TransactionOrderBuildEvent(oder.identifier,oder.seller,oder.sellObject,oder.stackAmount,oder.allowbuyer,oder.exemptedovertimelosses); return true; } //Set the address of the specified buyer and trader, which can be set directly in sell, or set the value to address (0) in sell to ensure that everyone can buy, and then call this function to set function setallowbuyer(uint256 _identifier,address _allowbuyer) public returns (bool) { TransactionOrder memory oder= AllTransactionOrders[_identifier]; require(oder.stackAmount>0,"cancel oder");//cancel Oder require(oder.seller==_msgSender(),"not owner"); require(oder.sellLock==false,"sell Locked");//锁了不能改 oder.allowbuyer=_allowbuyer; AllTransactionOrders[_identifier]=oder; return true; } //The buyer wants to buy the order and pledge his eusdt function Buy(uint256 _identifier) public lock returns (bool) { require(Address.isContract(_msgSender())==false,"not hunman"); require(!TransactionBan[_msgSender()],"Transaction ban"); //获得订单 require(AllTransactionOrders[_identifier].seller!=address(0),"null oder");//空订单 require(AllTransactionOrders[_identifier].stackAmount>0,"cancel oder");//cancel Oder require(AllTransactionOrders[_identifier].sellLock==false,"sell Locked");//卖方未锁定 if(AllTransactionOrders[_identifier].allowbuyer!=address(0)){ require(AllTransactionOrders[_identifier].allowbuyer==_msgSender(),"you are not allowbuyer");//卖方未锁定 } uint256 _buyerStackAmount=AllTransactionOrders[_identifier].stackAmount.div(3).mul(1); require(IERC20(EUSDTAddress).balanceOf(_msgSender())>=_buyerStackAmount,"The number of remaining tokens in the seller is insufficient"); require(IERC20(EUSDTAddress).allowance(_msgSender(),address(this))>=_buyerStackAmount,"Insufficient number of eusdt approvals");// IERC20(EUSDTAddress).safeTransferFrom(_msgSender(),address(this),_buyerStackAmount); //不为空的buyer给他还回去 if(AllTransactionOrders[_identifier].buyer!=address(0)){ IERC20(EUSDTAddress).safeTransfer(AllTransactionOrders[_identifier].buyer, AllTransactionOrders[_identifier].buyerstackAmount); } //buy oder AllTransactionOrders[_identifier].buyer=_msgSender(); AllTransactionOrders[_identifier].buyerstackAmount=_buyerStackAmount; return true; } //Seller lock , confirm transaction function SellLock(uint256 _identifier,uint256 _exemptedovertimelosses) public lock returns (bool) { require(Address.isContract(_msgSender())==false,"not hunman"); //获得订单 require(AllTransactionOrders[_identifier].stackAmount>0,"cancel oder");//cancel Oder require( AllTransactionOrders[_identifier].sellLock==false,"sell Locked");//没有锁 require( AllTransactionOrders[_identifier].buyer!=address(0),"buyer can not empty");//得有买家 require( AllTransactionOrders[_identifier].seller==_msgSender(),"not seller");//得是卖家 //sell lock AllTransactionOrders[_identifier].sellLock=true; AllTransactionOrders[_identifier].exemptedovertimelosses=_exemptedovertimelosses; return true; } //Buyer lock, confirm transaction function BuyLock(uint256 _identifier) public lock returns (bool) { require(Address.isContract(_msgSender())==false,"not hunman"); //获得订单 require(AllTransactionOrders[_identifier].stackAmount>0,"cancel oder");//cancel Oder require( AllTransactionOrders[_identifier].sellLock==true,"sell UnLocked");//卖方锁定 require( AllTransactionOrders[_identifier].buyLock==false,"buy Locked");//没有锁 require( AllTransactionOrders[_identifier].buyer==_msgSender(),"not seller");//得是买家 //sell lock AllTransactionOrders[_identifier].buyLock=true; //Lock time Lock_TransactionOrder_Time[_identifier]=block.timestamp; return true; } //Seller confirms receipt of cash function ReceiveUSDLock(uint256 _identifier) public lock returns (bool) { require(Address.isContract(_msgSender())==false,"not hunman"); //获得订单 require(AllTransactionOrders[_identifier].stackAmount>0,"cancel oder");//cancel Oder require( AllTransactionOrders[_identifier].buyLock==true,"buy UnLocked");//买家锁 require( AllTransactionOrders[_identifier].receiveUSD==false,"Received USD");//未确认收款 require( AllTransactionOrders[_identifier].seller==_msgSender(),"not seller");//得是卖家 //sell lock AllTransactionOrders[_identifier].receiveUSD=true; return true; } //Buyer confirms receipt of item function ReceiveObjectLock(uint256 _identifier) public lock returns (bool) { require(Address.isContract(_msgSender())==false,"not hunman"); //获得订单 require(AllTransactionOrders[_identifier].stackAmount>0,"cancel oder");//cancel Oder require( AllTransactionOrders[_identifier].receiveUSD==true,"Not Received USD");//确认收款 require( AllTransactionOrders[_identifier].receiveObject==false,"Received Object");//未确认收货 require( AllTransactionOrders[_identifier].buyer==_msgSender(),"not buyer");//得是买家 //sell lock AllTransactionOrders[_identifier].receiveObject=true; //CompleteTransaction uint256 sellSA=AllTransactionOrders[_identifier].stackAmount; uint256 buySA=AllTransactionOrders[_identifier].buyerstackAmount; //exemptedovertimelosses uint256 timeExempted=AllTransactionOrders[_identifier].exemptedovertimelosses; uint256 timeLock=Lock_TransactionOrder_Time[_identifier]; uint256 realTaxRate=taxRate; uint256 DeTime=block.timestamp-(timeLock+timeExempted); if(DeTime>0){ realTaxRate=realTaxRate.add(DeTime.div(86400).mul(100));//Lock timeout penalty tax rate, increased by 1% per day } //realTaxRate more than 100% if(realTaxRate>10000){ realTaxRate=10000;//set realTaxRate 100% } uint256 tx_seller=sellSA.div(10000).mul(realTaxRate);//min 0.01% uint256 tx_buyer=buySA.div(10000).mul(realTaxRate); allTax=allTax.add(tx_seller.add(tx_buyer));//all tax IERC20(EUSDTAddress).safeTransfer(AllTransactionOrders[_identifier].seller,sellSA.sub(tx_seller)); IERC20(EUSDTAddress).safeTransfer(AllTransactionOrders[_identifier].buyer,buySA.sub(tx_buyer)); return true; } // If the seller cancels the transaction order, this function can only be executed before the buyer locks it function SellerCancelOrder(uint256 _identifier) public lock returns (bool) { require(Address.isContract(_msgSender())==false,"not hunman"); //获得订单 require(AllTransactionOrders[_identifier].seller!=address(0),"null oder");//空订单 require(AllTransactionOrders[_identifier].stackAmount>0,"cancel oder");//cancel Oder require(AllTransactionOrders[_identifier].buyLock==false,"buy Locked");//卖方未锁定 require(AllTransactionOrders[_identifier].seller==_msgSender(),"not oder owner");//得是卖家 //tax cancelOrderTax uint256 SellerSA=AllTransactionOrders[_identifier].stackAmount; uint256 BuyerSA=AllTransactionOrders[_identifier].buyerstackAmount; uint256 tx_cancel=SellerSA.div(10000).mul(cancelOrderTax);//min 0.01% IERC20(EUSDTAddress).safeTransfer(AllTransactionOrders[_identifier].seller,SellerSA.sub(tx_cancel)); if(BuyerSA>0){ IERC20(EUSDTAddress).safeTransfer(AllTransactionOrders[_identifier].buyer,BuyerSA); } //cancelOrder AllTransactionOrders[_identifier].stackAmount=0; AllTransactionOrders[_identifier].buyerstackAmount=0; return true; } //If the buyer cancels the transaction order, this function can only be executed before the buyer is locked function BuyerCancelOrder(uint256 _identifier) public lock returns (bool) { require(Address.isContract(_msgSender())==false,"not hunman"); //获得订单 require(AllTransactionOrders[_identifier].seller!=address(0),"null oder");//空订单 require(AllTransactionOrders[_identifier].buyer==_msgSender(),"not oder owner");//得是卖家 require(AllTransactionOrders[_identifier].buyLock==false,"buy Locked");//卖方未锁定 require(AllTransactionOrders[_identifier].buyerstackAmount>0,"cancel oder");//cancel Oder //tax cancelOrderTax uint256 SellerSA=AllTransactionOrders[_identifier].stackAmount; uint256 BuyerSA=AllTransactionOrders[_identifier].buyerstackAmount; uint256 tx_cancel=BuyerSA.div(10000).mul(cancelOrderTax);//min 0.01% IERC20(EUSDTAddress).safeTransfer(AllTransactionOrders[_identifier].seller,SellerSA); IERC20(EUSDTAddress).safeTransfer(AllTransactionOrders[_identifier].buyer,BuyerSA.sub(tx_cancel)); //cancelOrder AllTransactionOrders[_identifier].stackAmount=0; AllTransactionOrders[_identifier].buyerstackAmount=0; return true; } //Get the real tax rate, including the lock timeout penalty tax rate function getRealTax(uint256 _identifier) public view returns (uint256) { //exemptedovertimelosses uint256 timeExempted=AllTransactionOrders[_identifier].exemptedovertimelosses; uint256 timeLock=Lock_TransactionOrder_Time[_identifier]; uint256 realTaxRate=taxRate; uint256 DeTime=block.timestamp-(timeLock+timeExempted); if(DeTime>0){ realTaxRate=realTaxRate.add(DeTime.div(86400).mul(100));//Lock timeout penalty tax rate, increased by 1% per day } //realTaxRate more than 100% if(realTaxRate>10000){ realTaxRate=10000;//set realTaxRate 100% } return realTaxRate; } //Administrator withdraws transaction tax income function withdrawTax(address _to) public onlyOwner lock returns (bool) { //sell lock require(Address.isContract(_msgSender())==false,"sender not hunman"); require(Address.isContract(_to)==false,"to address not hunman"); IERC20(EUSDTAddress).safeTransfer(_to,allTax); allTax=0; return true; } //Arbitration white list. This function is under discussion function setWhiteList(address[] memory users) public onlyOwner returns (bool) { uint len=users.length; for(uint i=0;i<len;i++){ WhiteList[WhiteListIndex]=users[i]; WhiteListIndex=WhiteListIndex.add(1); } emit SetWhiteListEvent(users); return true; } function getWhiteList() public view returns (address[] memory) { address[] memory users=new address[](WhiteListIndex); for(uint i=0;i<WhiteListIndex;i++){ users[i]=WhiteList[i]; } return users; } function isInWhiteList(address user) public view returns (bool) { for(uint i=0;i<WhiteListIndex;i++){ if(WhiteList[i]==user){ return true; } } return false; } //approve lock modifier lock(){ require(aproveunlocked==1,"LOCKED"); aproveunlocked=0; _; aproveunlocked=1; } }
Administrator withdraws transaction tax incomesell lock
function withdrawTax(address _to) public onlyOwner lock returns (bool) { require(Address.isContract(_msgSender())==false,"sender not hunman"); require(Address.isContract(_to)==false,"to address not hunman"); IERC20(EUSDTAddress).safeTransfer(_to,allTax); allTax=0; return true; }
12,536,198
pragma solidity ^0.4.2; contract Wolker { mapping (address => uint256) balances; mapping (address => uint256) allocations; mapping (address => mapping (address => uint256)) allowed; mapping (address => mapping (address => bool)) authorized; //trustee /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value, balances[msg.sender], balances[_to]); return true; } else { throw; } } /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { var _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value, balances[_from], balances[_to]); return true; } else { throw; } } /// @return total amount of tokens function totalSupply() external constant returns (uint256) { return generalTokens + reservedTokens; } /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of Wolk token to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @param _trustee Grant trustee permission to settle media spend /// @return Whether the authorization was successful or not function authorize(address _trustee) returns (bool success) { authorized[msg.sender][_trustee] = true; Authorization(msg.sender, _trustee); return true; } /// @param _trustee_to_remove Revoke trustee's permission on settle media spend /// @return Whether the deauthorization was successful or not function deauthorize(address _trustee_to_remove) returns (bool success) { authorized[msg.sender][_trustee_to_remove] = false; Deauthorization(msg.sender, _trustee_to_remove); return true; } // @param _owner // @param _trustee // @return authorization_status for platform settlement function check_authorization(address _owner, address _trustee) constant returns (bool authorization_status) { return authorized[_owner][_trustee]; } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } //**** ERC20 TOK Events: event Transfer(address indexed _from, address indexed _to, uint256 _value, uint from_final_tok, uint to_final_tok); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Authorization(address indexed _owner, address indexed _trustee); event Deauthorization(address indexed _owner, address indexed _trustee_to_remove); event NewOwner(address _newOwner); event MintEvent(uint reward_tok, address recipient); event LogRefund(address indexed _to, uint256 _value); event CreateWolk(address indexed _to, uint256 _value); event Vested(address indexed _to, uint256 _value); modifier onlyOwner { assert(msg.sender == owner); _; } modifier isOperational() { assert(isFinalized); _; } //**** ERC20 TOK fields: string public constant name = 'Wolk'; string public constant symbol = "WOLK"; string public constant version = "0.2"; uint256 public constant decimals = 18; uint256 public constant wolkFund = 10 * 10**1 * 10**decimals; // 100 Wolk in operation Fund uint256 public constant tokenCreationMin = 20 * 10**1 * 10**decimals; // 200 Wolk Min uint256 public constant tokenCreationMax = 100 * 10**1 * 10**decimals; // 1000 Wolk Max uint256 public constant tokenExchangeRate = 10000; // 10000 Wolk per 1 ETH uint256 public generalTokens = wolkFund; // tokens in circulation uint256 public reservedTokens; //address public owner = msg.sender; address public owner = 0xC28dA4d42866758d0Fc49a5A3948A1f43de491e9; // michael - main address public multisig_owner = 0x6968a9b90245cB9bD2506B9460e3D13ED4B2FD1e; // new multi-sig bool public isFinalized = false; // after token sale success, this is true uint public constant dust = 1000000 wei; bool public fairsale_protection = true; // Actual crowdsale uint256 public start_block; // Starting block uint256 public end_block; // Ending block uint256 public unlockedAt; // Unlocking block uint256 public end_ts; // Unix End time // minting support //uint public max_creation_rate_per_second; // Maximum token creation rate per second //address public minter_address; // Has permission to mint // migration support //address migrationMaster; //**** Constructor: function Wolk() { // Actual crowdsale start_block = 3831300; end_block = 3831900; // wolkFund is 100 balances[msg.sender] = wolkFund; // Wolk Inc has 25MM Wolk, 5MM of which is allocated for Wolk Inc Founding staff, who vest at "unlockedAt" time reservedTokens = 25 * 10**decimals; allocations[0x564a3f7d98Eb5B1791132F8875fef582d528d5Cf] = 20; // unassigned allocations[0x7f512CCFEF05F651A70Fa322Ce27F4ad79b74ffe] = 1; // Sourabh allocations[0x9D203A36cd61b21B7C8c7Da1d8eeB13f04bb24D9] = 2; // Michael - Test allocations[0x5fcf700654B8062B709a41527FAfCda367daE7b1] = 1; // Michael - Main allocations[0xC28dA4d42866758d0Fc49a5A3948A1f43de491e9] = 1; // Urmi CreateWolk(msg.sender, wolkFund); } // ****** VESTING SUPPORT /// @notice Allow developer to unlock allocated tokens by transferring them to developer's address on vesting schedule of "vested 100% on 1 year) function unlock() external { if (now < unlockedAt) throw; uint256 vested = allocations[msg.sender] * 10**decimals; if (vested < 0 ) throw; // Will fail if allocation (and therefore toTransfer) is 0. allocations[msg.sender] = 0; reservedTokens = safeSub(reservedTokens, vested); balances[msg.sender] = safeAdd(balances[msg.sender], vested); Vested(msg.sender, vested); } // ******* CROWDSALE SUPPORT // Accepts ETH and creates WOLK function createTokens() payable external is_not_dust { if (isFinalized) throw; if (block.number < start_block) throw; if (block.number > end_block) throw; if (msg.value == 0) throw; if (tx.gasprice > 0.021 szabo && fairsale_protection) throw; if (msg.value > 0.04 ether && fairsale_protection) throw; uint256 tokens = safeMul(msg.value, tokenExchangeRate); // check that we're not over totals uint256 checkedSupply = safeAdd(generalTokens, tokens); if ( checkedSupply > tokenCreationMax) { throw; // they need to get their money back if something goes wrong } else { generalTokens = checkedSupply; balances[msg.sender] = safeAdd(balances[msg.sender], tokens); // safeAdd not needed; bad semantics to use here CreateWolk(msg.sender, tokens); // logs token creation } } // The value of the message must be sufficiently large to not be considered dust. modifier is_not_dust { if (msg.value < dust) throw; _; } // Disabling fairsale protection function fairsale_protectionOFF() external { if ( block.number - start_block < 200) throw; // fairsale window is strictly enforced if ( msg.sender != owner ) throw; fairsale_protection = false; } // Finalizing the crowdsale function finalize() external { if ( isFinalized ) throw; if ( msg.sender != owner ) throw; // locks finalize to ETH owner if ( generalTokens < tokenCreationMin ) throw; // have to sell tokenCreationMin to finalize if ( block.number < end_block ) throw; isFinalized = true; end_ts = now; unlockedAt = end_ts + 2 minutes; if ( ! multisig_owner.send(this.balance) ) throw; } function refund() external { if ( isFinalized ) throw; if ( block.number < end_block ) throw; if ( generalTokens >= tokenCreationMin ) throw; if ( msg.sender == owner ) throw; uint256 Val = balances[msg.sender]; balances[msg.sender] = 0; generalTokens = safeSub(generalTokens, Val); uint256 ethVal = safeDiv(Val, tokenExchangeRate); LogRefund(msg.sender, ethVal); if ( ! msg.sender.send(ethVal) ) throw; } // ****** Platform Settlement function settleFrom(address _from, address _to, uint256 _value) isOperational() external returns (bool success) { if ( msg.sender != owner ) throw; var _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && (allowed[_from][msg.sender] >= _value || authorized[_from][msg.sender] == true ) && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); if ( allowed[_from][msg.sender] < 0 ){ allowed[_from][msg.sender] = 0; } Transfer(_from, _to, _value, balances[_from], balances[_to]); return true; } else { throw; } } // ****** MINTING SUPPORT // Mint new tokens modifier only_minter { assert(msg.sender == minter_address); _; } address public minter_address = owner; // Has permission to mint function mintTokens(uint reward_tok, address recipient) external payable only_minter { balances[recipient] = safeAdd(balances[recipient], reward_tok); generalTokens = safeAdd(generalTokens, reward_tok); MintEvent(reward_tok, recipient); } function changeMintingAddress(address newAddress) onlyOwner returns (bool success) { minter_address = newAddress; return true; } //**** SafeMath: function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) throw; } }
Finalizing the crowdsale
function finalize() external { if ( isFinalized ) throw; if ( block.number < end_block ) throw; isFinalized = true; end_ts = now; unlockedAt = end_ts + 2 minutes; if ( ! multisig_owner.send(this.balance) ) throw; }
5,363,292
./full_match/80001/0x609d55e56bE77041B589E6409EfB05Ac8d680707/sources/MasterChef2.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 foxReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); fox.mint(devAddress, foxReward.div(10)); fox.mint(address(this), foxReward); pool.accFoxPerShare = pool.accFoxPerShare.add(foxReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
871,424
pragma solidity ^0.4.21; import "./Secp256k1.sol"; import "./LinkableRingSignature.sol"; import "./owned.sol"; contract Voting is owned { enum State { SETUP, REGISTRATION, VOTING, READY_TO_TALLY, END_TALLY } State public state; modifier inState(State s) { if(state != s) { throw; } _; } /**************************************** SETUP DATA /****************************************/ string public electionName; //uint public votingStartTime; //uint public votingEndTime; uint public numberOfVoters; uint public numberOfCandidates; bytes32[] public candidates; mapping(bytes32 => bool) public candidatesMap; /**************************************** END SETUP DATA /****************************************/ /**************************************** REGISTRATION DATA /****************************************/ uint256[] public ring; uint256 public ringHash; uint256[2][] public voters; //voters publickeys [X,Y] mapping(bytes32 => bool) public registeredKeys; /**************************************** END REGISTRATION DATA /****************************************/ bool public debug = true; /**************************************** VOTE DATA /****************************************/ mapping(bytes32 => bool) public registeredVoteLink; //to verify if voter has already voted bytes32[] public votes; uint256[] public hashedVotes; /**************************************** END VOTE DATA /****************************************/ mapping(bytes32 => uint256) public electionResults; /************************************** */ function Voting() { state = State.SETUP; } // @dev Sets a contract to debug mode so election times can be ignored. // Can only be called by owner. function setDebug() inState(State.SETUP) onlyOwner() { debug = true; } function finishSetUp( string _electionName, // uint _votingStartTime, // uint _votingEndTime, uint _numberOfVoters, uint _numberOfCandidates, bytes32[] _candidates //,uint256[2][] _publicKeys ) inState(State.SETUP) onlyOwner() returns (bool) { /* if(_registrationStartTime < block.timestamp) { return false; } if(Secp256k1.isPubKey(_thresholdKey) == false) { return false; } */ if(_numberOfCandidates < 2) { return false; } if(_numberOfVoters < 2) { return false; } electionName = _electionName; numberOfCandidates = _numberOfCandidates; numberOfVoters = _numberOfVoters; // votingStartTime = _votingStartTime; // votingEndTime = _votingEndTime; //state = State.VOTING; candidates = _candidates; for (uint i=0;i<numberOfCandidates;i++) { candidatesMap[_candidates[i]] = true; } state = State.REGISTRATION; return true; } function registerVoter(uint256[2] publicKey) inState(State.REGISTRATION) onlyOwner returns (bool){ // if(block.timestamp > registrationEndTime + registrationVotingGap) { // state = State.VOTING; // return false; // } // if(block.timestamp > registrationEndTime) { // return false; // } if(Secp256k1.isPubKey(publicKey) == false) { return false; } if(registeredKeys[sha3(publicKey)]) { return false; } ring.push(publicKey[0]); ring.push(publicKey[1]); voters.push([publicKey[0], publicKey[1]]); registeredKeys[sha3(publicKey)] = true; return true; } function endRegistrationPhase() inState(State.REGISTRATION) onlyOwner returns (bool) { // if(!debug) { // if(block.timestamp < registrationEndTime) { // return false; // } // } if(ring.length / 2 == numberOfVoters) { ringHash = LinkableRingSignature.hashToInt(ring); state = State.VOTING; return true; } else return false; } function endVotingPhase() inState(State.VOTING) onlyOwner returns (bool) { // if(!debug) { // if(block.timestamp < votingEndTime) { // return false; //} //} state = State.READY_TO_TALLY; return true; } function bytesToBytes32(bytes b) returns (bytes32) { bytes32 result; assembly { result := mload(add(b, 32)) } return result; } function castVote( uint256 hashedVote, bytes vote, uint256[] pubKeys, uint256 c_0, uint256[] signature, uint256[2] link) inState(State.VOTING) returns (bool,uint){ bytes32 linkedH = sha3(link); if(registeredVoteLink[linkedH]) { return (false,0); } if(candidatesMap[bytesToBytes32(vote)] == false) { return (false,1); } uint256 _ringHash = LinkableRingSignature.hashToInt(pubKeys); if( ringHash != _ringHash) { return (false,2); } if( hashedVote != uint256(sha3(vote))) { return (false,5); } if(LinkableRingSignature.verifyRingSignature(hashedVote, pubKeys, c_0, signature, link)) { hashedVotes.push(hashedVote); votes.push(bytesToBytes32(vote)); registeredVoteLink[linkedH] = true; return (true,3); } return (false,4); } function tallyElection() inState(State.READY_TO_TALLY) onlyOwner constant { //initialize for( uint i =0; i < candidates.length; i++ ) { electionResults[candidates[i]] = 0;} //count votes for( uint j = 0; j < votes.length; j++) { electionResults[votes[j]] += 1;} state = State.END_TALLY; } function getCandidateCount(bytes32 candidate) inState(State.END_TALLY) constant returns(uint256) { return electionResults[candidate]; } function getCandidates() constant returns (bytes32[]){ return candidates; } function getRingSize(uint ringIdx) constant returns (uint) { return ring.length; } function getNumberCastedVotes() constant returns (uint) { return votes.length; } function getNumRegisterVoters() constant returns (uint) { return voters.length; } }
Sets a contract to debug mode so election times can be ignored. Can only be called by owner.
function setDebug() inState(State.SETUP) onlyOwner() { debug = true; }
2,497,267
pragma solidity ^0.4.25; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract FlightSuretyData flightSuretyData; //data contract instance /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(isOperational(), "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @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 "isAirlineExists" boolean variable to be "false" */ modifier isAirlineExists(address airlineAddress) { // Modify to call data contract's status require(!flightSuretyData.isAirlineExists(airlineAddress), "Airline already Registered"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "hasAirlineFunded" boolean variable to be "false" */ modifier hasAirlineFunded(address airlineAddress) { // Modify to call data contract's status require(flightSuretyData.hasAirlineFunded(airlineAddress), "Airline has not funded the contract"); _; // All modifiers require an "_" which indicates where the function body will be added } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address dataContract) public { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(dataContract); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns (bool) { return flightSuretyData.isOperational(); // Modify to call data contract's status } function isAirline(address addRess) public view returns (bool) { return flightSuretyData.isAirlineExists(addRess); } /** * @dev method to check if airline already registered or not. called from app contract */ function isAirlineFunded(address airlineAddress) external view requireIsOperational returns (bool) { return flightSuretyData.hasAirlineFunded(airlineAddress); } /** * @dev gets airlineInitialFundAmount */ function airlineFundFee() public view returns (uint256) { return flightSuretyData.getAirlineInitialFundAmount(); } /** * @dev return users wallet balance * */ function getMyWalletBalance() public view requireIsOperational returns (uint256) { return flightSuretyData.getUserBalance(msg.sender); } /// @notice converts number to string /// @dev source: https://github.com/provable-things/ethereum-api/blob/master/oraclizeAPI_0.5.sol#L1045 /// @param _i integer to convert /// @return _uintAsString function uintToStr(uint256 _i) internal pure returns (string memory _uintAsString) { uint256 number = _i; if (number == 0) { return "0"; } uint256 j = number; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (number != 0) { bstr[k--] = bytes1(uint8(48 + (number % 10))); number /= 10; } return string(bstr); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * empty airlines name not allowed */ function registerAirline(address airlineAddress, string name) external requireIsOperational isAirlineExists(airlineAddress) // checking if airline is already registered returns (bool success, uint256 votes) { bytes memory tempEmptyStringTest = bytes(name); require(tempEmptyStringTest.length > 0, "Airline name not provided"); //fail fast if airline name is empty // address[] registeredAirlineArray; address[] memory getRegisteredAirlineArr = flightSuretyData.getRegisteredAirlineArr(); if (getRegisteredAirlineArr.length < 4) { require( flightSuretyData.isAirlineExists(msg.sender), "Only Registered Airline can registered another airline till total registered airlins are upto 4" ); require(flightSuretyData.hasAirlineFunded(msg.sender), "Only Airlines who have funded the contract are eligible to register another airline"); flightSuretyData.registerAirline(airlineAddress, name); return (true, 0); } else { uint256 voteRequired = getRegisteredAirlineArr.length.div(2); //fifty percent required if (getRegisteredAirlineArr.length % 2 != 0) voteRequired = voteRequired + 1; // upperbound we take. i.e if 7/2, we need four vots not 3.5 uint256 voteGained = 0; bool isDuplicate = false; //check if msg.sender already added provided airline to pool. if (!flightSuretyData.isAirlinInForRegistration(airlineAddress, msg.sender)) { //if not, then add this airline to pool and wait for 50% vote. //note : this does not mean one vote is given, it just means pooling. vote count will be calculated later in the method flightSuretyData.addToNewAirlineVotePool(airlineAddress, msg.sender); } else { //fail fast if (!flightSuretyData.hasAirlineFunded(msg.sender)) { require(!true, "You have already added this airline in registration pool, you need to fund to cast your vote."); } isDuplicate = true; } uint256 totalRegisteredAirlines = getRegisteredAirlineArr.length; for (uint256 i = 0; i < totalRegisteredAirlines; i++) { //check if the airlin to be registered is already in pool and the msg.sender has funded. if both true, increment one vote. if (flightSuretyData.addedToPoolAndHasFunded(airlineAddress, getRegisteredAirlineArr[i])) { voteGained = voteGained + 1; } if (voteGained == voteRequired) { //we have got enought vote, now register the airline flightSuretyData.registerAirline(airlineAddress, name); //delete all references from storage, as it is no longer required in pending pool flightSuretyData.deletePendingAirlineFromPool(airlineAddress); return (true, voteGained); } } // no need for this require statement, i have included it to show proper test error during testing require( isDuplicate == false, string( abi.encodePacked( "Not enought vote gained, more vote needed = ", uintToStr(voteRequired - voteGained), ", total registered = ", uintToStr(totalRegisteredAirlines), ", voteRequired = ", uintToStr(voteRequired), ", vote gained = ", uintToStr(voteGained) ) ) ); return (false, voteGained); } } /** * @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() public payable requireIsOperational { //check if amount is ok. require( msg.value == flightSuretyData.getAirlineInitialFundAmount(), string(abi.encodePacked("Invalid amount sent. Check valid amount using getAirlineInitialFundAmount")) ); flightSuretyData.fund.value(msg.value)(msg.sender); } /** * @dev Register a future flight for insuring. * */ function registerFlight(string flight, uint256 timestamp) public requireIsOperational { require(flightSuretyData.isAirlineExists(msg.sender), "Only Registered Airline can register flights"); require(flightSuretyData.hasAirlineFunded(msg.sender), "Only Airlines who have funded the contract can register its flights"); flightSuretyData.registerFlight(msg.sender, flight, timestamp); } event AmountTransferedToUser(address indexed userWalletAddress, uint256 amount); /** * @dev send back insuance amount to user account from userwallet balance * */ function withdraw() public requireIsOperational { uint256 userBalance = flightSuretyData.getUserBalance(msg.sender); require(userBalance > 0, "User balance is nil"); flightSuretyData.pay(msg.sender); emit AmountTransferedToUser(msg.sender, userBalance); } /** * user will call this method from dapp to buy insurance */ function buyInsurance( address airline, string flight, uint256 timestamp ) public payable requireIsOperational { require(flightSuretyData.isAirlineExists(airline), "Airline not registered with us"); require(flightSuretyData.hasAirlineFunded(airline), "Airline has not funded contract"); require(now < timestamp, "Insurance for flight which have alredy flew not allowed."); require( msg.value > 0 && msg.value <= flightSuretyData.getFlightInsuranceCapAmount(), "Invalid insurance buying amount, call getFlightInsuranceCapAmount to know allowed range" ); require(!flightSuretyData.isInsuranceAlreadyBought(airline, flight, timestamp), "You have already bought insurance for this flight"); flightSuretyData.buy.value(msg.value)(airline, flight, timestamp, msg.sender); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus( address airline, string memory flight, uint256 timestamp, uint8 statusCode ) internal requireIsOperational { require(flightSuretyData.isAirlineExists(airline), "Airline not registered with us"); require(flightSuretyData.hasAirlineFunded(airline), "Airline has not funded contract"); //return money if filght delayed if (statusCode == STATUS_CODE_LATE_AIRLINE) { //initiat credit to user wallet, transfer only when user call withdraw method flightSuretyData.creditInsurees(keccak256(abi.encodePacked(airline, flight, timestamp))); } else { //noting to do for know, FlightStatusInfo event already called } } // Generate a request for oracles to fetch flight information function fetchFlightStatus( address airline, string flight, uint256 timestamp ) public { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 1; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); // Register an oracle with the contract function registerOracle() external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes() external view returns (uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse( uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode ) public { require( (oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request" ); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { delete oracleResponses[key]; emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey( address airline, string flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns (uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while (indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion } contract FlightSuretyData { function isOperational() external view returns (bool); function isAirlineExists(address) external view returns (bool); function hasAirlineFunded(address airlineAddress) external view returns (bool); function getRegisteredAirlineArr() external view returns (address[] memory); function registerAirline(address airlineAddress, string name) external; function isAirlinInForRegistration(address pendingAirline, address registeredAirline) external view returns (bool); function addToNewAirlineVotePool(address newAirlineToBeRegistrered, address msgSenderAddress) external; function addedToPoolAndHasFunded(address pendingRegistration, address msgSenderAddress) external view returns (bool); function deletePendingAirlineFromPool(address pendingAirline) external; function getAirlineInitialFundAmount() external view returns (uint256); function fund(address senderAddress) external payable; //airline need to fund before talkin part in contract function registerFlight( address airline, string flight, uint256 timestamp ) external; function pay(address userAddress) external; // called to transfer money to user account 1.5 times of insurance amount function getUserBalance(address userAddress) external view returns (uint256); function creditInsurees(bytes32 flightKey) external; //called to credit userbalance for fligh delay function buy( address airline, string flight, uint256 timestamp, address userAddress ) external payable; //called to buy insurance function getFlightInsuranceCapAmount() external view returns (uint256); function isFlightExists( address airline, string flight, uint256 timestamp ) external view returns (bool); function isInsuranceAlreadyBought( address airline, string flight, uint256 timestamp ) external view returns (bool); }
gets airlineInitialFundAmount/
function airlineFundFee() public view returns (uint256) { return flightSuretyData.getAirlineInitialFundAmount(); }
12,688,859
contract IPOI { // Idea object struct Idea { uint32 id; address owner; address[] parties; uint256 date; string description; bytes proofDoc; } // State variable to hold ID of next idea uint32 numIdeaId; //Mapping of Idea datatypes mapping(uint => Idea) ideas; // Maps owner to their ideas mapping(address => uint32[]) ownerIdeas; // Owner address public owner; // Fee to use the service uint public fee; //Set owner and fee function IPOI(uint feeParam) { owner = msg.sender; fee = feeParam; } // Change contract fee function changeContractFee(uint newFee) onlyowner { fee = newFee; } // Create initial idea contract function createIdea(address ideaOwner, address[] partiesEntry, string descriptionEntry) onlyowner returns(uint32 ideaId) { if (msg.value >= fee) { if (msg.value > fee) { msg.sender.send(msg.value - fee); //payed more than required => refund } ideaId = numIdeaId++; Idea idea = ideas[ideaId]; ownerIdeas[ideaOwner].push(ideaId); idea.id = ideaId; idea.owner = ideaOwner; for (uint i = 0; i < partiesEntry.length; i++) { idea.parties.push(partiesEntry[i]); } idea.date = now; idea.description = descriptionEntry; IdeaChangeEvent(idea.date, "IPOI Contract Creation", bytes(descriptionEntry)); } } // Get idea by the address owner dadress function getIdea(address ideaOwner) returns(uint32[]) { return ownerIdeas[ideaOwner]; } // Get idea date by ID function getIdeaDate(uint ideaId) returns(uint ideaDate) { return ideas[ideaId].date; } // Get idea description by ID function getIdeaDescription(uint ideaId) returns(string ideaDescription) { return ideas[ideaId].description; } // Get idea parties by ID function getIdeaParties(uint ideaId) returns(address[] ideaParties) { return ideas[ideaId].parties; } // Get owner of contract function getOwner() returns(address owner) { return owner; } // Upload documentation for proof of idea (signed signatures?) function ideaProofDocument(bytes IPOIProofHash, uint ideaId) onlyowner { ideas[ideaId].proofDoc = IPOIProofHash; IdeaChangeEvent(block.timestamp, "Entered Idea Proof Document", "Idea proof in IPFS"); } // Declare event structure event IdeaChangeEvent(uint256 date, bytes indexed name, bytes indexed description); function destroy() { if (msg.sender == owner) { suicide(owner); // send any funds to owner } } modifier onlyowner() { if (msg.sender == owner) _ } // This function gets executed if a transaction with invalid data is sent to // the contract or just ether without data. We revert the send so that no-one // accidentally loses money when using the contract. function() { throw; } }
Change contract fee
function changeContractFee(uint newFee) onlyowner { fee = newFee; }
908,270
./full_match/1/0x0B85b96Da3672da00B071cB1905E6AE5948a7975/sources/DegenData-Paywall/degendata-access.sol
ADMIN FUNCTIONS sets new `owner` state variable. Granting new owner control to admin functions. address.New address to be set.
function setNewOwner(address _newOwner) public onlyOwner { owner = _newOwner; }
3,062,872
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "../RrpRequester.sol"; /// @title A mock Airnode RRP requester contract contract MockRrpRequester is RrpRequester { event FulfilledRequest(bytes32 indexed requestId, bytes data); mapping(bytes32 => bytes) public requestIdToData; mapping(bytes32 => bool) private expectingRequestWithIdToBeFulfilled; /// @param airnodeRrpAddress Airnode RRP contract address constructor(address airnodeRrpAddress) RrpRequester(airnodeRrpAddress) {} /// @notice A wrapper for the respective method at AirnodeRrp.sol for /// testing /// @param templateId Template ID /// @param sponsor Sponsor address /// @param sponsorWallet Sponsor wallet that is requested to fulfill /// the request /// @param fulfillAddress Address that will be called to fulfill /// @param fulfillFunctionId Signature of the function that will be called /// to fulfill /// @param parameters Parameters provided by the requester in addition to /// the parameters in the template function makeTemplateRequest( bytes32 templateId, address sponsor, address sponsorWallet, address fulfillAddress, bytes4 fulfillFunctionId, bytes calldata parameters ) external { bytes32 requestId = airnodeRrp.makeTemplateRequest( templateId, sponsor, sponsorWallet, fulfillAddress, fulfillFunctionId, parameters ); expectingRequestWithIdToBeFulfilled[requestId] = true; } /// @notice A wrapper for the respective method at AirnodeRrp.sol for /// testing /// @param airnode Airnode address /// @param endpointId Endpoint ID /// @param sponsor Sponsor address /// @param sponsorWallet Sponsor wallet that is requested to fulfill /// the request /// @param fulfillAddress Address that will be called to fulfill /// @param fulfillFunctionId Signature of the function that will be called /// to fulfill /// @param parameters All request parameters function makeFullRequest( address airnode, bytes32 endpointId, address sponsor, address sponsorWallet, address fulfillAddress, bytes4 fulfillFunctionId, bytes calldata parameters ) external { bytes32 requestId = airnodeRrp.makeFullRequest( airnode, endpointId, sponsor, sponsorWallet, fulfillAddress, fulfillFunctionId, parameters ); expectingRequestWithIdToBeFulfilled[requestId] = true; } /// @notice A method to be called back by the respective method at /// AirnodeRrp.sol for testing /// @param requestId Request ID /// @param data Data returned by the Airnode function fulfill(bytes32 requestId, bytes calldata data) external onlyAirnodeRrp { require( expectingRequestWithIdToBeFulfilled[requestId], "No such request made" ); delete expectingRequestWithIdToBeFulfilled[requestId]; requestIdToData[requestId] = data; emit FulfilledRequest(requestId, data); } /// @notice A method to be called back by the respective method at /// AirnodeRrp.sol for testing fulfillment failure /// @param requestId Request ID /// @param data Data returned by the Airnode function fulfillAlwaysReverts( bytes32 requestId, // solhint-disable-line no-unused-vars bytes calldata data // solhint-disable-line no-unused-vars ) external view onlyAirnodeRrp { revert("Always reverts"); } /// @notice A method to be called back by the respective method at /// AirnodeRrp.sol for testing fulfillment failure /// @param requestId Request ID /// @param data Data returned by the Airnode function fulfillAlwaysRevertsWithNoString( bytes32 requestId, // solhint-disable-line no-unused-vars bytes calldata data // solhint-disable-line no-unused-vars ) external view onlyAirnodeRrp { revert(); // solhint-disable-line reason-string } /// @notice A method to be called back by the respective method at /// AirnodeRrp.sol for testing fulfillment running out of gas /// @param requestId Request ID /// @param data Data returned by the Airnode function fulfillAlwaysRunsOutOfGas( bytes32 requestId, // solhint-disable-line no-unused-vars bytes calldata data // solhint-disable-line no-unused-vars ) external view onlyAirnodeRrp { while (true) {} } /// @notice A wrapper for the respective method at AirnodeRrp.sol for /// testing /// @dev The withdrawal requested by calling this will revert because this /// contract does not implement a default payable method /// @param airnode Airnode address /// @param sponsorWallet Sponsor wallet that the withdrawal is requested /// from function requestWithdrawal(address airnode, address sponsorWallet) external { airnodeRrp.requestWithdrawal(airnode, sponsorWallet); } }
A method to be called back by the respective method at AirnodeRrp.sol for testing fulfillment failure requestId Request ID data Data returned by the Airnode
function fulfillAlwaysRevertsWithNoString( ) external view onlyAirnodeRrp { }
1,048,269
// SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.0; /* ▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▐░░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░▌░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▀▀▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▐░▌▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░░▌▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▀ ▀▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ████ ████▓▓▓▓████ ██▓▓▓▓▓▓▓▓▓▓▓▓██ ██▓▓▓▓▓▓▓▓▓▓████████ ████ ██▓▓▓▓▓▓████░░░░██ ██░░░░██ ██▓▓▓▓██░░░░░░░░░░██ ██░░░░██ ██▓▓▓▓██░░░░░░░░░░██ ██░░░░██ ██▓▓██░░░░░░░░░░██ ██░░░░░░██ ██░░░░░░░░░░░░██ ██░░░░██ ██░░░░░░░░██ ██░░██ ██████░░░░████████ ██░░██ ████░░░░██████░░░░░░██ ██░░██ ████░░░░████░░░░██░░░░░░░░██ ██░░██ ████░░░░░░░░░░░░████░░░░░░░░░░██ ██░░░░████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░██ ██░░░░██░░░░░░░░░░░░░░░░░░░░░░░░░░░░██░░██ ██░░░░██░░░░████░░░░░░░░░░░░░░░░░░░░██░░██ ██░░░░██████ ██░░░░░░░░░░░░░░░░░░░░██████ ████ ██░░░░░░░░░░░░░░░░░░░░██░░██ ██░░░░░░░░░░░░░░░░░░░░██░░██ ██░░░░░░░░░░░░░░░░░░░░██░░██ ██░░░░░░░░░░░░░░░░░░░░██░░██ ██░░░░░░░░░░░░░░░░░░░░██░░██ ██░░░░░░░░░░░░░░░░░░░░██░░██ */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev 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; } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @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); } /** * @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); } /** * @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); } 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); } } } } /** * @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; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @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); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } interface TraitDB { function viewTrait(uint256 _id) external view returns (string memory); function totalTraits() external view returns (uint256); } /** * @title NPCs: Genesis Edition * @dev {ERC721} token built on OpenZeppelin & Loot (licensed under MIT), including: * - token minting (creation) for Loot & xLoot holders at discount * - URI autogeneration from svg * - Compound-style governance * The traits listed in quotation marks under the headers contract AttrSpawnLocation, * contract AttrOutfit, contract AttrAttitude, contract AttrHands, contract AttrPockets, * contract AttrLove, contract AttrSecret, contract AttrHabitus in the smart contracts * referenced by this smart contract are licensed under the Creative Commons * Attribution 4.0 International License (“CC 4.0”). To view a copy of this license, * visit http://creativecommons.org/licenses/by/4.0/ or send a letter to Creative Commons, * PO Box 1866, Mountain View, CA 94042, USA. For avoidance of doubt, combinations of such traits * generated by this smart contract are also licensed under CC 4.0. For purposes of attribution, * the creator of these traits is the NPC Genesis Project (designed by Josh Garcia and Diana Stern). */ contract NPCs is ERC721("NPCs: Genesis Edition", "NPCS"), ERC721Enumerable, Ownable, ReentrancyGuard { /// @dev Loot contract is available at https://etherscan.io/address/0xff9c1b15b16263c61d017ee9f65c50e4ae0113d7. IERC721Enumerable public loot = IERC721Enumerable(0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7); /// @dev xLoot contract is available at https://etherscan.io/address/0x8bf2f876E2dCD2CAe9C3d272f325776c82DA366d. IERC721Enumerable public xLoot = IERC721Enumerable(0x8bf2f876E2dCD2CAe9C3d272f325776c82DA366d); /// @notice A record of each account's delegate. mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block. struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A 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 An event thats emitted when an account changes its delegate. event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes. event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); TraitDB public spawnLocationDB; TraitDB public outfitDB; TraitDB public attitudeDB; TraitDB public handsDB; TraitDB public pocketsDB; TraitDB public loveDB; TraitDB public secretDB; TraitDB public habitusDB; constructor( address _defaultLocation, address _outfit, address _attitude, address _hands, address _pockets, address _love, address _secret, address _habitus ) { spawnLocationDB = TraitDB(_defaultLocation); outfitDB = TraitDB(_outfit); attitudeDB = TraitDB(_attitude); handsDB = TraitDB(_hands); pocketsDB = TraitDB(_pockets); loveDB = TraitDB(_love); secretDB = TraitDB(_secret); habitusDB = TraitDB(_habitus); } function random(string memory input) private pure returns (uint256 rand) { rand = uint256(keccak256(abi.encodePacked(input))); } function getLocation(uint256 tokenId) public view returns (string memory location) { uint256 index = randomIndex(tokenId, "LOCATION", spawnLocationDB.totalTraits()); location = spawnLocationDB.viewTrait(index); } function getOutfit(uint256 tokenId) public view returns (string memory outfit) { uint256 index = randomIndex(tokenId, "OUTFIT", outfitDB.totalTraits()); outfit = outfitDB.viewTrait(index); } function getAttitude(uint256 tokenId) public view returns (string memory attitude) { uint256 index = randomIndex(tokenId, "ATTITUDE", attitudeDB.totalTraits()); attitude = attitudeDB.viewTrait(index); } function getHands(uint256 tokenId) public view returns (string memory hands) { uint256 index = randomIndex(tokenId, "HANDS", handsDB.totalTraits()); hands = handsDB.viewTrait(index); } function getPockets(uint256 tokenId) public view returns (string memory pockets) { uint256 index = randomIndex(tokenId, "POCKETS", pocketsDB.totalTraits()); pockets = pocketsDB.viewTrait(index); } function getLove(uint256 tokenId) public view returns (string memory love) { uint256 index = randomIndex(tokenId, "LOVE", loveDB.totalTraits()); love = loveDB.viewTrait(index); } function getSecret(uint256 tokenId) public view returns (string memory secret) { uint256 index = randomIndex(tokenId, "SECRET", secretDB.totalTraits()); secret = secretDB.viewTrait(index); } function getHabitus(uint256 tokenId) public view returns (string memory habitus) { uint256 index = randomIndex(tokenId, "HABITUS", habitusDB.totalTraits()); habitus = habitusDB.viewTrait(index); } function randomIndex(uint256 tokenId, string memory keyPrefix, uint256 size) private pure returns (uint256 index) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); index = rand % size; } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) private pure returns (string memory output) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); output = sourceArray[rand % sourceArray.length]; } function tokenURI(uint256 tokenId) override public view returns (string memory output) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getLocation(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getOutfit(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getAttitude(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getHands(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getPockets(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getLove(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getSecret(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; parts[15] = getHabitus(tokenId); parts[16] = '</text></svg>'; output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16])); string memory payload = string(abi.encodePacked( '{"name": "NPC #', toString(tokenId), '", "description": "NPCs are random onchain characters with stories to tell for Loot & xLoot Adventurers", "attributes": [{"trait_type": "SpawnLocation","value": "', getLocation(tokenId), '"}, {"trait_type": "Outfit","value": "', getOutfit(tokenId), '"}, {"trait_type": "Attitude","value": "', getAttitude(tokenId), '"}, {"trait_type": "Hands","value": "' )); payload = string(abi.encodePacked( payload, getHands(tokenId), '"}, {"trait_type": "Pockets","value": "', getPockets(tokenId), '"}, {"trait_type": "Love","value": "', getLove(tokenId), '"}, {"trait_type": "Secret","value": "', getSecret(tokenId), '"}, {"trait_type": "Habitus","value": "', getHabitus(tokenId), '"}], "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}' )); string memory json = Base64.encode(bytes(payload)); output = string(abi.encodePacked('data:application/json;base64,', json)); } /** * @dev Creates a new NPC token for `_msgSender()`. The token * URI is autogenerated based on 'METADATA MAGICK' and ID matches Loot/xLoot holdings, after ETH fee. * * See {ERC721-_mint}. */ function claim(uint256 tokenId) external nonReentrant payable { // @dev Check caller owns Loot/xLoot to mint NPC. if (tokenId < 8001) { // @dev confirm Loot ownership / discount require( _msgSender() == loot.ownerOf(tokenId), "MUST_OWN_LOOT_ID"); require(msg.value == 0.025 ether, "INSUFF_ETH"); } else if (tokenId > 8000 && tokenId < 16001) { // @dev confirm xLoot ownership / discount require( _msgSender() == xLoot.ownerOf(tokenId), "MUST_OWN_XLOOT_ID"); require(msg.value == 0.025 ether, "INSUFF_ETH"); } else { // @dev public mint remainder before reserve require(tokenId < 19501, "OUT_OF_BOUNDS"); require(msg.value == 0.05 ether, "INSUFF_ETH"); } _safeMint(_msgSender(), tokenId); } function ownerClaim(uint256 tokenId) external nonReentrant onlyOwner { require(tokenId > 19500 && tokenId < 20001, "OUT_OF_BOUNDS"); _safeMint(_msgSender(), tokenId); } /** * @dev Allows `owner` to collect NFT minting fees in ETH. */ function collectETH() external nonReentrant onlyOwner { (bool success, ) = _msgSender().call{value: address(this).balance}(""); require(success, "NOT_PAYABLE"); } function toString(uint256 value) private pure returns (string memory output) { // @dev 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); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(_msgSender(), delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96) { require(blockNumber < block.number, "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) private { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = uint96(balanceOf(delegator)); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) private { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) private { uint32 blockNumber = safe32(block.number, "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) private pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() private view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /// **** OZ HELPERS **** /// function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); _moveDelegates(delegates[from], delegates[to], 1); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } /// [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); } }
Delegate votes from `msg.sender` to `delegatee` delegatee The address to delegate votes to/
function delegate(address delegatee) external { return _delegate(_msgSender(), delegatee); }
288,480
pragma solidity ^0.8.6; import "./FlightSuretyData.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; // to typecase variable types safely import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ /// @author Dinesh B S contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /*******************************************************************/ /* DATA VARIABLES */ /*******************************************************************/ // Flight status codes uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract FlightSuretyData private dataContract; struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } mapping(bytes32 => Flight) private flights; uint256 constant MINIMUM_FUNDING = 10 ether; uint8 constant MAXIMUM_OWNERS_TO_NOT_VOTE = 4; /*******************************************************************/ /* FUNCTION MODIFIERS */ /*******************************************************************/ /** * @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(isOperational(), "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"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires acitivated airlines to call the function */ modifier requireActivatedAirline() { require(isActivatedAirline(msg.sender), "The Airline is not active"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires a register airline to call the function */ modifier requireRegisteredAirline() { require(isRegisteredAirline(msg.sender), "Airline is not registered"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the minimum funding requirement to satisfied */ modifier requireMinimumFunding() { require(msg.value >= MINIMUM_FUNDING, "Airline initial funding isn't sufficient"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires an activated airline or the owner to call the function */ modifier requireActivatedAirlineOrContractOwner() { require(isActivatedAirline(msg.sender) || (msg.sender == contractOwner), "Caller must be either the owner or an active airline"); _; // All modifiers require an "_" which indicates where the function body will be added } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address payable addressDataContract) { contractOwner = msg.sender; dataContract = FlightSuretyData(addressDataContract); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns (bool) { return dataContract.isOperational(); } /** * @dev Determines whether an airline is registered */ function isRegisteredAirline(address addressAirline) private view returns (bool registered) { (uint8 id, , , , , ) = dataContract.getAirline(addressAirline); registered = (id != 0); } /** * @dev Sets contract operations to pause or resume */ function setOperatingStatus(bool newMode) external requireContractOwner { dataContract.setOperatingStatus(newMode); } /** * @dev Returns if an airline is active */ function isActivatedAirline(address addressAirline) private view returns (bool activated) { (, , , , activated, ) = dataContract.getAirline(addressAirline); } /******************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /******************************************************************************/ /** * @dev Add an airline to the registration queue **/ function registerAirline(address airlineAddress, string calldata airlineName) external requireIsOperational requireActivatedAirlineOrContractOwner { if (dataContract.getAirlineId(airlineAddress) != 0) { _voteAirline(airlineAddress); // vote } else { _registerNewAirline(airlineAddress, airlineName); // Request for new registration } } /** * @dev Register a future flight for insuring. * */ function registerFlight(string calldata _flight, uint256 _newTimestamp) external requireActivatedAirline { bytes32 key = getFlightKey(msg.sender, _flight, _newTimestamp); // key for uniqueness flights[key] = Flight({ isRegistered: true, statusCode: STATUS_CODE_UNKNOWN, updatedTimestamp: _newTimestamp, airline: msg.sender }); } function getInsurance(address _airline, string calldata _flight, uint256 _timestamp) external view returns ( uint256 amount, uint256 claimAmount, uint8 status ) { bytes32 key = getFlightKey(_airline, _flight, _timestamp); // key for uniqueness (amount, claimAmount, status) = dataContract.getInsurance(msg.sender, key); } function fetchFlight(address _airline, string calldata _flight, uint256 _timestamp) external view returns ( uint256 timestamp, uint8 statusCode, string memory airlineName ) { bytes32 key = getFlightKey(_airline, _flight, _timestamp); statusCode = flights[key].statusCode; timestamp = flights[key].updatedTimestamp; (, airlineName, , , , ) = dataContract.getAirline(_airline); } function buyInsurance(address _airline, string calldata _flight, uint256 _timestamp) external payable { require(msg.value > 0, "Cannot send 0 ether"); bytes32 key = getFlightKey(_airline, _flight, _timestamp); if (msg.value <= 1 ether) { dataContract.addInsurance(msg.sender, key, msg.value); return; } // If the value sent is more than 1 ether, return the excess amount as 1 ether is the maximum insurance amount dataContract.addInsurance(msg.sender, key, 1 ether); address payable toSender = payable(msg.sender); uint excessAmount = msg.value - 1 ether; toSender.transfer(excessAmount); } function withDrawInsurance(address _airline, string calldata _flight, uint256 _timestamp) external { bytes32 key = getFlightKey(_airline, _flight, _timestamp); (, uint256 claimAmount, uint8 status) = dataContract.getInsurance(msg.sender, key); require(status == 1, "Insurance is not claimed"); dataContract.withdrawInsurance(msg.sender, key); address payable toSender = payable(msg.sender); toSender.transfer(claimAmount); } function claimInsurance(address _airline, string calldata _flight, uint256 _timestamp) external { bytes32 key = getFlightKey(_airline, _flight, _timestamp); // key for uniqueness require(flights[key].statusCode == STATUS_CODE_LATE_AIRLINE, "Airline is not late due its own fault"); (uint256 amount, , uint8 status) = dataContract.getInsurance(msg.sender, key); require(amount > 0, "Insurance is not bought"); require(status == 0, "Insurance is already claimed"); uint256 amountToClaim = amount.mul(150).div(100); // 1.5 times amount spent on insurance is retured when the flight is delayed dataContract.claimInsurance(msg.sender, key, amountToClaim); } /** * @dev Called after oracle has updated flight status */ function processFlightStatus(address _airline, string memory _flight, uint256 _timestamp, uint8 statusCode) internal { bytes32 key = getFlightKey(_airline, _flight, _timestamp); flights[key].statusCode = statusCode; } // Generate a request for oracles to fetch flight information function fetchFlightStatus( address airline, string calldata flight, uint256 timestamp ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256( abi.encodePacked(index, airline, flight, timestamp) ); ResponseInfo storage responseInfo = oracleResponses[key]; // to resolve the issue caused by updated version in solidity responseInfo.requester = msg.sender; responseInfo.isOpen = true; emit OracleRequest(index, airline, flight, timestamp); } fallback() external payable { _receiveAirlineFunds(); } receive() external payable { _receiveAirlineFunds(); } function _receiveAirlineFunds() /// '_' respresents a private function private requireRegisteredAirline requireMinimumFunding { dataContract.addAirlineBalance(msg.sender, msg.value); dataContract.activateAirline(msg.sender); } function _voteAirline(address addressAirline) private { /// '_' respresents a private function uint256 airlineVoteCount = SafeCast.toUint256( dataContract.voteAirline(msg.sender, addressAirline) ); uint256 totalAirlineCount = dataContract.getTotalCountAirlines() - 1; uint value = airlineVoteCount.mul(100).div(totalAirlineCount); if (value >= 50) { dataContract.approveAirline(addressAirline); } } function _registerNewAirline(address addressAirline, string memory nameAirline) private { /// '_' respresents a private function dataContract.registerAirline( msg.sender, addressAirline, nameAirline, dataContract.getTotalCountAirlines() < MAXIMUM_OWNERS_TO_NOT_VOTE // consensus ); } // ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo( address airline, string flight, uint256 timestamp, uint8 status ); event OracleReport( address airline, string flight, uint256 timestamp, uint8 status ); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest( uint8 index, address airline, string flight, uint256 timestamp ); // Register an oracle with the contract function registerOracle() external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes() external view returns (uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse( uint8 index, address airline, string calldata flight, uint256 timestamp, uint8 statusCode ) external { require( (oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request" ); bytes32 key = keccak256( abi.encodePacked(index, airline, flight, timestamp) ); require( oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request" ); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey( address airline, string memory flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns (uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while (indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8( uint256( keccak256(abi.encodePacked(blockhash(block.number - nonce++), account)) ) % maxValue ); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
Returns if an airline is active/
function isActivatedAirline(address addressAirline) private view returns (bool activated) { (, , , , activated, ) = dataContract.getAirline(addressAirline); }
6,486,448
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Register.sol"; import "Agora.sol"; import "Loi.sol"; import "Delegation.sol"; import "Citizens_Register.sol"; import "IVote.sol"; library Constitution_Register{ function Create_Loi(address agora)external returns(address){ Loi loi = new Loi(agora); //loi.Add_Authority(authority); return address(loi); } function Create_Citizens(address[] calldata Initial_members, address token_address, uint new_citizen_mint_amount)external returns(address){ return address(new Citizens_Register(Initial_members, token_address, new_citizen_mint_amount)); } } library Constitution_Delegation{ function Create_Delegation(address[] memory Initial_members, address Token_Address, address citizen_address, address agora_address)external returns(address){ Delegation delegation = new Delegation(Initial_members, Token_Address, citizen_address, agora_address); return address(delegation); } } //contract Constitution is Register, IConstitution_Agora, IConstitution_Delegation{ contract Constitution is Register{ using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint; //using Constitution_Register for Constitution_Register.Register_Parameters; //using Constitution_Delegation for Constitution_Delegation.Delegation_Parameters; //using SafeMath for uint8; /* struct Register_Parameters{ //uint Index; // index in Registers_Address_List array uint Actual_Version; uint Petition_Duration; uint Vote_Duration; uint Vote_Checking_Duration; uint Helper_Max_Duration; uint Law_Initialisation_Price; uint FunctionCall_Price; uint Helper_Amount_Escrow; uint16 Assembly_Max_Members; uint16 Description_Max_Size; uint8 FunctionCall_Max_Number; uint8 Required_Petition_Rate; uint8 Representatives_Rates; uint8 Voters_Reward_Rate; uint8 Helper_Reward_Rate; uint8 Assembly_Voluteer_Reward_Rate; uint8 OffChain_Delegation_Reward; uint8 Vote_Type; uint8 Register_Type; address OffChain_Vote_Delegation; // Delegation in charge of filling in on chain the result of the off-chain vote address Assembly_Associated_Delegation; // Delegation allowed to take part in the Agora Assembly in charge of voting for the good proposition }*/ /*struct Register_Parameters{ uint Index; // index in Registers_Address_List array uint8 Register_Type; mapping(uint=>Referendum_Parameters) Parameter_Versions; uint Actual_Version; }*/ /*struct Delegation_Parameters{ //uint Index; //uint Revert_Penalty_Limit; uint Legislatif_Process_Version; uint Internal_Governance_Version; uint Member_Max_Token_Usage; uint Law_Initialisation_Price; uint FunctionCall_Price; uint Proposition_Duration; uint Vote_Duration; uint Election_Duration; uint Law_Revertable_Period_Duration; uint Mandate_Duration; uint Immunity_Duration; uint16 Num_Max_Members; uint8 Revert_Proposition_Petition_Rate; uint8 New_Election_Petition_Rate; uint8 Revert_Penalty_Rate; EnumerableSet.AddressSet Controled_Register; }*/ event Register_Parameters_Modified(address); Agora public Agora_Instance; Citizens_Register public Citizen_Instance; DemoCoin public Democoin; IVote public majority_judgment_ballot; //address public Citizens_Address; address public Transitional_Government; //mapping(address=>Constitution_Register.Register_Parameters) Registers; EnumerableSet.AddressSet Registers_Address_List; //mapping(address=>Constitution_Delegation.Delegation_Parameters) Delegations; EnumerableSet.AddressSet Delegation_Address_List; address public Citizen_Registering_Address; //uint8 public Account_Max_Token_Rate; //Each account can't pocess more than "Account_Max_Token_Rate"% of the entire token supply. constructor(address transition_government, address[] memory initial_citizens, string memory Token_Name, string memory Token_Symbole, uint[] memory initial_citizens_token_amount, uint new_citizen_mint_amount){ require(transition_government !=address(0)); Constitution_Address = address(this); //Type_Institution = Institution_Type.CONSTITUTION; Democoin = new DemoCoin(Token_Name, Token_Symbole, initial_citizens, initial_citizens_token_amount); Citizen_Instance = new Citizens_Register(initial_citizens, address(Democoin), new_citizen_mint_amount); Agora_Instance = new Agora(address(Democoin), address(Citizen_Instance)); //majority_judgment_ballot = new majority_judgment_ballot(); //Citizens_Address = Constitution_Register.Create_Citizens(initial_citizens); Transitional_Government = transition_government; Register_Authorities.add(Transitional_Government); Register_Authorities.add(address(Agora_Instance)); } function End_Transition_Government()external{ require(msg.sender == Transitional_Government, "Transitional_Government only"); Register_Authorities.remove(Transitional_Government); } /*FUNCTIONCALL API functions*/ function Set_Citizen_Mint_Amount(uint amount) external Register_Authorities_Only{ Citizen_Instance.Set_Citizen_Mint_Amount(amount); } function Set_Minnter(address[] calldata Add_Minter, address[] calldata Remove_Minter)external Register_Authorities_Only{ uint add_len=Add_Minter.length; uint remove_len = Remove_Minter.length; for(uint i =0; i<add_len;i++){ Democoin.Add_Minter(Add_Minter[i]); } for(uint j=0; j<remove_len; j++){ Democoin.Remove_Minter(Remove_Minter[j]); } } function Set_Burner(address[] calldata Add_Burner, address[] calldata Remove_Burner)external Register_Authorities_Only{ uint add_len=Add_Burner.length; uint remove_len = Remove_Burner.length; for(uint i =0; i<add_len;i++){ Democoin.Add_Burner(Add_Burner[i]); } for(uint j=0; j<remove_len; j++){ Democoin.Remove_Burner(Remove_Burner[j]); } } /*Citizens_Register Handling*/ function Citizen_Register_Remove_Authority(address removed_authority) external Register_Authorities_Only{ Citizen_Instance.Remove_Authority(removed_authority); } function Add_Registering_Authority(address new_authority)external Register_Authorities_Only{ Citizen_Instance.Add_Registering_Authority(new_authority); } /*function Remove_Registering_Authority(address removed_authority)external Register_Authorities_Only{ Citizen_Instance.Remove_Registering_Authority(removed_authority); }*/ function Add_Banning_Authority(address new_authority)external Register_Authorities_Only{ Citizen_Instance.Add_Banning_Authority(new_authority); } /*function Remove_Banning_Authority(address removed_authority)external Register_Authorities_Only{ Citizen_Instance.Remove_Banning_Authority(removed_authority); }*/ /*Register/Agora Handling*/ function Create_Register(uint8 register_type, uint[7] calldata Uint256_Arg, uint16 Assembly_Max_Members, uint8[6] calldata Uint8_Arg, address Assembly_Associated_Delegation, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ address new_register_address; if(register_type == 0){ new_register_address = address(this); }else if(register_type == 1){ /*Register new_register = new Loi(); new_register_address= address(new_register); new_register.Add_Authority(address(Agora_Instance));*/ new_register_address = Constitution_Register.Create_Loi(address(Agora_Instance)); }else if(register_type == 2){ }else{ //return (false, bytes("Not Register Type")); revert("Not Register Type"); } require(!Registers_Address_List.contains(new_register_address), "Register Already Existing"); if(Assembly_Associated_Delegation != address(0) && !Delegation_Address_List.contains(Assembly_Associated_Delegation)){ //return (false, bytes("Delegation doesn't exist")); revert("Delegation doesn't exist"); } Registers_Address_List.add(new_register_address); Agora_Instance.Create_Register_Referendum(new_register_address, register_type); _Set_Register_Param( new_register_address, Uint256_Arg, Assembly_Max_Members, Uint8_Arg, Assembly_Associated_Delegation, Ivote_address); //Registers[new_register_address].Register_Type = register_type; //Registers[new_register_address].Actual_Version = 1; emit Register_Parameters_Modified(new_register_address); //return (true, bytes("")); //return Registers[new_register_address]._Set_Register_Param(new_register_address, Uint256_Arg, Uint16_Arg, Uint8_Arg, OffChain_Vote_Delegation, Assembly_Associated_Delegation); } function Set_Register_Param(address register_address, uint[7] calldata Uint256_Arg, uint16 Assembly_Max_Members, uint8[6] calldata Uint8_Arg, address Assembly_Associated_Delegation, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ //uint version = Registers[register_address].Actual_Version; require(Registers_Address_List.contains(register_address), "Register doesn't exist"); /*if( Delegations[Assembly_Associated_Delegation].Num_Max_Members ==0 && Assembly_Associated_Delegation != address(0)){ //return (false, bytes("Delegation doesn't exist")); revert("Delegation doesn't exist"); }*/ _Set_Register_Param(register_address, Uint256_Arg, Assembly_Max_Members, Uint8_Arg, Assembly_Associated_Delegation, Ivote_address); emit Register_Parameters_Modified(register_address); //return (success, data); //return Registers[register_address]._Set_Register_Param( Uint256_Arg, Assembly_Max_Members, Uint8_Arg, OffChain_Vote_Delegation, Assembly_Associated_Delegation); } function _Set_Register_Param(address register_address, uint[7] calldata Uint256_Arg, uint16 Assembly_Max_Members, uint8[6] calldata Uint8_Arg, address Assembly_Associated_Delegation, address Ivote_address) internal {//returns(bool, bytes memory){ //uint version =register.Actual_Version; if(Uint256_Arg[0] ==0 || Uint256_Arg[1] ==0 || Uint256_Arg[3]==0 || Uint8_Arg[0] == 0 || Uint8_Arg[0] >100 || Uint8_Arg[1]>100 || Ivote_address==address(0)){ //return (false, bytes("Bad arguments value")); revert("Bad arguments value"); } //uint temp = uint(Uint8_Arg[3]).add(uint(Uint8_Arg[4]).add(uint(Uint8_Arg[5]).add(uint(Uint8_Arg[6])))); if(uint(Uint8_Arg[2]).add(uint(Uint8_Arg[3]).add(uint(Uint8_Arg[4]).add(uint(Uint8_Arg[5])))) != 100 || (Assembly_Max_Members ==0 && Uint8_Arg[4]>0) || Uint8_Arg[1]>100 || (Assembly_Associated_Delegation != address(0) && Uint8_Arg[1]==0)){ //return (false, bytes("Reward inconsistency")); revert("Reward inconsistency"); } Agora_Instance.Update_Register_Referendum_Parameters(register_address,Uint256_Arg, Assembly_Max_Members, Uint8_Arg, Assembly_Associated_Delegation, Ivote_address); //Registers[register_param].Set_Register(Uint256_Arg, Uint16_Arg, Uint8_Arg, OffChain_Vote_Delegation, Assembly_Associated_Delegation); } /*Delegations Handling*/ function Create_Delegation(address delegation_address, uint[6] calldata Uint256_Legislatifs_Arg, uint[5] calldata Uint256_Governance_Arg, uint16 Num_Max_Members, uint8 Revert_Proposition_Petition_Rate, uint8 Revert_Penalty_Rate, uint8 New_Election_Petition_Rate, address[] memory Initial_members, address Ivote_address_legislatif, address Ivote_address_governance) external Register_Authorities_Only { if(Uint256_Legislatifs_Arg[3]==0 || Uint256_Legislatifs_Arg[4]==0 || Revert_Proposition_Petition_Rate>100 || Revert_Penalty_Rate>100 || Ivote_address_legislatif==address(0)){ //return(false, bytes("Bad Argument Value")); revert("Legislatif: Bad Argument Value"); } if(Uint256_Governance_Arg[0]==0 || Uint256_Governance_Arg[1]==0 || Num_Max_Members==0 || New_Election_Petition_Rate ==0 || New_Election_Petition_Rate>100 || Initial_members.length <= Num_Max_Members || Ivote_address_governance==address(0)){ //return(false, bytes("Bad Argument Value")); revert("Governance: Bad Argument Value"); } if(delegation_address == address(0)){ //Create a new delegation /*Delegation Delegation_Instance = new Delegation(Initial_members, address(Democoin)); delegation_address = address(Delegation_Instance);*/ for(uint i =0; i<Initial_members.length; i++){ require(Citizen_Instance.Contains(Initial_members[i]), "member is not citizen"); } delegation_address = Constitution_Delegation.Create_Delegation( Initial_members, address(Democoin), address(Citizen_Instance), address(Agora_Instance)); }else{ require(!Delegation_Address_List.contains(delegation_address), "Delegation already registered"); //return(false,bytes("Delegation already registered")); } Delegation(delegation_address).Update_Legislatif_Process(Uint256_Legislatifs_Arg[0], Uint256_Legislatifs_Arg[1], Uint256_Legislatifs_Arg[2], Uint256_Legislatifs_Arg[3], Uint256_Legislatifs_Arg[4], Uint256_Legislatifs_Arg[5], Revert_Proposition_Petition_Rate, Revert_Penalty_Rate, Ivote_address_legislatif); Delegation(delegation_address).Update_Internal_Governance(Uint256_Governance_Arg[0], Uint256_Governance_Arg[1], Uint256_Governance_Arg[2], Uint256_Governance_Arg[3], Num_Max_Members, New_Election_Petition_Rate, Ivote_address_governance); //Delegations[delegation_address]._Set_Delegation_Legislatif_Process(Uint256_Legislatifs_Arg[0], Uint256_Legislatifs_Arg[1], Uint256_Legislatifs_Arg[2], Uint256_Legislatifs_Arg[3], Uint256_Legislatifs_Arg[4], Uint256_Legislatifs_Arg[5], Revert_Proposition_Petition_Rate, Revert_Penalty_Rate); //Delegations[delegation_address]._Set_Delegation_Internal_Governance(Uint256_Governance_Arg[0], Uint256_Governance_Arg[1], Uint256_Governance_Arg[2], Num_Max_Members, New_Election_Petition_Rate); Delegation_Address_List.add(delegation_address); if(Uint256_Governance_Arg[4]>0){ Democoin.Mint(delegation_address, Uint256_Governance_Arg[3]); } } /* 0x0000000000000000000000000000000000000000, [15,5,1, 1000, 2000, 500], [1000, 10000,3000, 40] 20, 30, 20, 50*/ function Add_Delegation_Controled_Register(address delegation_address, address new_controled_register) external{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); require(Registers_Address_List.contains(new_controled_register), "Non Existing Register"); Register(new_controled_register).Add_Authority(delegation_address); //Add the delegation address to the authority list of registers whose address is in "add_controled_register" Delegation(delegation_address).Add_Controled_Register( new_controled_register); } function Remove_Delegation_Controled_Register(address delegation_address, address removed_controled_register) external{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); require(Registers_Address_List.contains(removed_controled_register), "Non Existing Register"); Delegation(delegation_address).Remove_Controled_Register( removed_controled_register); //The removal of the delegation address from the authority list of registers whose address is in "remove_controled_register" is left to the delegation. } function Set_Delegation_Legislatif_Process(address delegation_address, uint Member_Max_Token_Usage, uint Law_Initialisation_Price, uint FunctionCall_Price, uint Proposition_Duration, uint Vote_Duration, uint Law_Revertable_Period_Duration, uint8 Revert_Proposition_Petition_Rate, uint8 Revert_Penalty_Rate, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); if(Proposition_Duration==0 || Vote_Duration==0 || Revert_Proposition_Petition_Rate>100 || Revert_Penalty_Rate>100 ){ //return(false, bytes("Bad Argument Value")); revert("Bad Argument Value"); } Delegation(delegation_address).Update_Legislatif_Process(Member_Max_Token_Usage, Law_Initialisation_Price, FunctionCall_Price, Proposition_Duration, Vote_Duration, Law_Revertable_Period_Duration, Revert_Proposition_Petition_Rate, Revert_Penalty_Rate, Ivote_address); //Delegations[delegation_address]._Set_Delegation_Legislatif_Process(Member_Max_Token_Usage, Law_Initialisation_Price, FunctionCall_Price, Proposition_Duration, Vote_Duration, Law_Revertable_Period_Duration, Revert_Proposition_Petition_Rate, Revert_Penalty_Rate); } function Set_Delegation_Internal_Governance(address delegation_address, uint Election_Duration, uint Mandate_Duration, uint Immunity_Duration, uint Validation_Duration, uint16 Num_Max_Members, uint8 New_Election_Petition_Rate, uint Mint_Token, address Ivote_address) external Register_Authorities_Only{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); if(Election_Duration==0 || Mandate_Duration==0 || Num_Max_Members==0 || New_Election_Petition_Rate ==0 || New_Election_Petition_Rate>100 ){ revert("Bad Argument Value"); } if(Mint_Token>0){ Democoin.Mint(delegation_address, Mint_Token); } Delegation(delegation_address).Update_Internal_Governance(Election_Duration, Validation_Duration, Mandate_Duration, Immunity_Duration, Num_Max_Members, New_Election_Petition_Rate, Ivote_address); } /*function _Set_Delegation_Legislatif_Process( uint Member_Max_Token_Usage, uint Law_Initialisation_Price, uint FunctionCall_Price, uint Proposition_Duration, uint Vote_Duration, uint Law_Revertable_Period_Duration, uint8 Revert_Proposition_Petition_Rate, uint8 Revert_Penalty_Rate) external{ //returns(bool, bytes memory){ if(Proposition_Duration==0 || Vote_Duration==0 || Revert_Proposition_Petition_Rate>100 || Revert_Penalty_Rate>100 ){ //return(false, bytes("Bad Argument Value")); revert("Bad Argument Value"); } //if(Revert_Penalty_Rate>0 && Percentage(Revert_Penalty_Rate, FunctionCall_Price)) delegation.Legislatif_Process_Version = delegation.Legislatif_Process_Version.add(1); delegation.Member_Max_Token_Usage = Member_Max_Token_Usage; delegation.Law_Initialisation_Price = Law_Initialisation_Price; delegation.FunctionCall_Price = FunctionCall_Price; delegation.Proposition_Duration = Proposition_Duration; delegation.Vote_Duration = Vote_Duration; delegation.Law_Revertable_Period_Duration = Law_Revertable_Period_Duration; delegation.Revert_Proposition_Petition_Rate = Revert_Proposition_Petition_Rate; delegation.Revert_Penalty_Rate = Revert_Penalty_Rate; //return (true,bytes("")); } function _Set_Delegation_Internal_Governance( uint Election_Duration, uint Mandate_Duration, uint Immunity_Duration, uint16 Num_Max_Members, uint8 New_Election_Petition_Rate) external{ // returns(bool, bytes memory){ if(Election_Duration==0 || Mandate_Duration==0 || Num_Max_Members==0 || New_Election_Petition_Rate ==0 || New_Election_Petition_Rate>100 ){ //return(false, bytes("Bad Argument Value")); revert("Bad Argument Value"); } delegation.Internal_Governance_Version = delegation.Internal_Governance_Version.add(1); delegation.Election_Duration = Election_Duration; delegation.Mandate_Duration = Mandate_Duration; delegation.Immunity_Duration = Immunity_Duration; delegation.Num_Max_Members = Num_Max_Members; delegation.New_Election_Petition_Rate = New_Election_Petition_Rate; //return (true,bytes("")); }*/ /*GETTERS*/ function Get_Register_List() external view returns(bytes32[] memory){ return Registers_Address_List._inner._values; } /*function Get_Register_Parameter(address register) external view override returns(uint,uint){ return (Registers[register].Actual_Version, Registers[register].Register_Type); } function Get_Register_Referendum_Parameters(address register) external view override returns(uint[7] memory Uint256_Arg, uint16 Assembly_Max_Members, uint8[7] memory Uint8_Arg, address OffChain_Vote_Delegation, address Assembly_Associated_Delegation){ (Uint256_Arg, Assembly_Max_Members, Uint8_Arg, OffChain_Vote_Delegation, Assembly_Associated_Delegation)=Registers[register].Get_Register(); } function Get_Delegation_Legislatif_Process_Versions(address delegation_address) external view override returns(uint){ require(Delegations[delegation_address].Legislatif_Process_Version != 0, "Non existing Delegation"); return(Delegations[delegation_address].Legislatif_Process_Version); } function Get_Delegation_Internal_Governance_Versions(address delegation_address) external view override returns(uint){ require(Delegations[delegation_address].Legislatif_Process_Version != 0, "Non existing Delegation"); return( Delegations[delegation_address].Internal_Governance_Version); } function Get_Delegation_Legislation_Process(address delegation_address) external view override returns(uint[6] memory Uint256_Arg, uint8 Revert_Proposition_Petition_Rate, uint8 Revert_Penalty_Rate){ require(Delegations[delegation_address].Legislatif_Process_Version != 0, "Non existing Delegation"); return Delegations[delegation_address]._Get_Delegation_Legislatif_Process(); } function Get_Delegation_Internal_Governance(address delegation_address) external view override returns(uint Election_Duration, uint Mandate_Duration, uint Immunity_Duration, uint16 Num_Max_Members, uint8 New_Election_Petition_Rate){ require(Delegations[delegation_address].Legislatif_Process_Version != 0, "Non existing Delegation"); return Delegations[delegation_address]._Get_Delegation_Internal_Governance(); } */ function Get_Delegation_List() external view returns(bytes32[] memory){ return Delegation_Address_List._inner._values; } } /* [777,333,123,33,12,77,40] 20 [30,3,20,30,30,20,0] */ /* contract Agora is Institution{ using EnumerableSet for EnumerableSet.AddressSet; enum Status{ PETITIONS, VOTE, VOTE_CHECKING, EXECUTED, ABORTED } struct Register_Referendum{ uint Last_Version; Institution_Type Type; bytes32[] Failed_Referendums; EnumerableSet.Bytes32Set Pending_Referendums; bytes32[] Achieved_Referendums; } struct Referendum{ mapping(address=>bool) Petition; EnumerableSet.AddressSet Assembly_Volunteer; uint Petition_Counter; Status Referendum_Status; } Constitution Constitution_Instance; mapping(address=>Register_Referendum) Registers_Referendums; mapping(bytes32=>Referendum) Referendums; function Add_Law_Project(address register_address, bytes calldata Title, bytes calldata Description)external{ Constitution_Instance.Get_Register(register_address); //Add_Law_Project(Title, Description); } /*Overite functions*/ /*function Before_Add_Law_Project(bytes calldata Title, bytes calldata Description) internal override returns(bytes32){ } function Before_Add_Corpus_Proposal(bytes32 law_project, uint Parent, uint[] calldata Parent_Proposals_Reuse, bytes[] calldata New_Function_Call, bytes calldata Description) internal override{ } function Before_Add_Item_Proposal(bytes32 law_project, uint Proposal, bytes[] calldata New_Items, uint[] calldata Indexs) internal override{ }*/ //}
return (true,bytes(""));GETTERS/
function Get_Register_List() external view returns(bytes32[] memory){ return Registers_Address_List._inner._values; }
7,245,170
/* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.24; /** * @title IExchangeWrapper * @author Set Protocol * * Interface for executing an order with an exchange wrapper */ interface IExchangeWrapper { /* ============ External Functions ============ */ /** * Exchange some amount of makerToken for takerToken. * * @param _maker Issuance order maker * @param _taker Issuance order taker * @param _makerToken Address of maker token used in exchange orders * @param _makerAssetAmount Amount of issuance order maker token to use on this exchange * @param _orderCount Expected number of orders to execute * @param _orderData Arbitrary bytes data for any information to pass to the exchange * @return address[] The addresses of required components * @return uint256[] The quantities of required components retrieved by the wrapper */ function exchange( address _maker, address _taker, address _makerToken, uint256 _makerAssetAmount, uint256 _orderCount, bytes _orderData ) external returns (address[], uint256[]); }
IExchangeWrapper Set Protocol Interface for executing an order with an exchange wrapper/
interface IExchangeWrapper { function exchange( address _maker, address _taker, address _makerToken, uint256 _makerAssetAmount, uint256 _orderCount, bytes _orderData ) external returns (address[], uint256[]); Copyright 2018 Set Labs Inc. }
14,038,795
pragma solidity ^0.4.10; import '../common/Owned.sol'; /* based on https://gist.github.com/Arachnid/4ca9da48d51e23e5cfe0f0e14dd6318f */ /** * Base contract that all upgradeable contracts should use. * * Contracts implementing this interface are all called using delegatecall from * a dispatcher. As a result, the _sizes and _dest variables are shared with the * dispatcher contract, which allows the called contract to update these at will. * * _sizes is a map of function signatures to return value sizes. Due to EVM * limitations, these need to be populated by the target contract, so the * dispatcher knows how many bytes of data to return from called functions. * Unfortunately, this makes variable-length return values impossible. * * _dest is the address of the contract currently implementing all the * functionality of the composite contract. Contracts should update this by * calling the internal function `replace`, which updates _dest and calls * `initialize()` on the new contract. * * When upgrading a contract, restrictions on permissible changes to the set of * storage variables must be observed. New variables may be added, but existing * ones may not be deleted or replaced. Changing variable names is acceptable. * Structs in arrays may not be modified, but structs in maps can be, following * the same rules described above. */ contract Upgradeable { mapping(bytes4=>uint32) public _sizes; address public _dest; event TestEvent(bytes4 sig, uint32 len, address sender, address target); /** * This function is called using delegatecall from the dispatcher when the * target contract is first initialized. It should use this opportunity to * insert any return data sizes in _sizes, and perform any other upgrades * necessary to change over from the old contract implementation (if any). * * Implementers of this function should either perform strictly harmless, * idempotent operations like setting return sizes, or use some form of * access control, to prevent outside callers. */ function initialize(); /** * Performs a handover to a new implementing contract. */ function replace(address target) internal { _dest = target; target.delegatecall(bytes4(sha3("initialize()"))); } } /** * The dispatcher is a minimal 'shim' that dispatches calls to a targeted * contract. Calls are made using 'delegatecall', meaning all storage and value * is kept on the dispatcher. As a result, when the target is updated, the new * contract inherits all the stored data and value from the old contract. */ contract Dispatcher is Upgradeable { event TestEvent(bytes4 sig, uint32 len, address sender, address target); function Dispatcher(address target) { replace(target); } function initialize() { // Should only be called by on target contracts, not on the dispatcher require(false); } function changeTarget(address target) { replace(target); } function() { bytes4 sig; assembly { sig := calldataload(0) } uint32 len = _sizes[sig]; address target = _dest; bool callResult; //TestEvent(sig, len, msg.sender, target); assembly { // return _dest.delegatecall(msg.data) calldatacopy(0x0, 0x0, calldatasize) callResult := delegatecall(sub(gas, 10000), target, 0x0, calldatasize, 0, len) } require (callResult); assembly { return(0, len) } } }
Should only be called by on target contracts, not on the dispatcher
function initialize() { require(false); }
14,089,943
./full_match/8453/0xB287fA676198938fC2a098a546bF9e0368FF58Ad/sources/src/plugins/governance/multisig/IMultisig.sol
IMultisig Aragon Association - 2023 An interface for an on-chain multisig governance plugin in which a proposal passes if X out of Y approvals are met.
interface IMultisig { function addAddresses(address[] calldata _members) external; function removeAddresses(address[] calldata _members) external; function approve(uint256 _proposalId, bool _tryExecution) external; function canApprove(uint256 _proposalId, address _account) external view returns (bool); function canExecute(uint256 _proposalId) external view returns (bool); function hasApproved(uint256 _proposalId, address _account) external view returns (bool); function execute(uint256 _proposalId) external; import {IDAO} from "../../../core/dao/IDAO.sol"; }
11,550,350
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IMasterChefV1 { function withdraw(uint256 _pid, uint256 _amount) external; function deposit(uint256 _pid, uint256 _amount) external; } abstract contract BaseServer is Ownable { IMasterChefV1 public constant masterchefV1 = IMasterChefV1(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd); IERC20 public constant sushi = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); uint256 public immutable pid; address public immutable minichef; event Harvest(uint256 indexed pid); event Withdraw(uint256 indexed pid, uint256 indexed amount); event Deposit(uint256 indexed pid, uint256 indexed amount); constructor(uint256 _pid, address _minichef) { pid = _pid; minichef = _minichef; } function harvestAndBridge() public { masterchefV1.withdraw(pid, 0); bridge(); emit Harvest(pid); } function withdraw() public onlyOwner { masterchefV1.withdraw(pid, 1); emit Withdraw(pid, 1); } function deposit(address token) public onlyOwner { IERC20(token).approve(address(masterchefV1), 1); masterchefV1.deposit(pid, 1); emit Deposit(pid, 1); } function bridge() public virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../BaseServer.sol'; interface ICeloBridge { function send(address _token, uint256 _amount, uint32 _destination, bytes32 _recipient) external; } contract CeloServer is BaseServer { address public constant bridgeAddr = 0x6a39909e805A3eaDd2b61fFf61147796ca6aBB47; event BridgedSushi(address indexed minichef, uint256 indexed amount); constructor(uint256 _pid, address _minichef) BaseServer(_pid, _minichef) {} function bridge() public override { uint256 sushiBalance = sushi.balanceOf(address(this)); sushi.approve(bridgeAddr, sushiBalance); ICeloBridge(bridgeAddr).send(address(sushi), sushiBalance, 1667591279, bytes32(uint256(uint160(minichef)))); emit BridgedSushi(minichef, sushiBalance); } }
SPDX-License-Identifier: MIT
interface ICeloBridge { function send(address _token, uint256 _amount, uint32 _destination, bytes32 _recipient) external; }
13,508,029
./full_match/421613/0x1474236fEB9E96Cf0B9f913fF5418856139caAe3/sources/contracts/Game.sol
function to see the total reeemed rewards from the basket. Only the owner of the basket can view this. _basketId Basket ID (tokenID) in the BasketToken (NFT) contract. return int256 Total redeemed rewards.
function basketRedeemedRewards( uint256 _basketId ) external view onlyBasketOwner(_basketId) returns (int) { return baskets[_basketId].totalRedeemedRewards; }
11,576,154
import "../user/contracts/UserManager.sol"; import "../project/contracts/ProjectManager.sol"; /** * Interface to global contracts */ contract AdminInterface { // NOTE: variable name must match contract name UserManager public userManager; ProjectManager public projectManager; /** * Constructor. Initialize global contracts and pointers */ function AdminInterface() { userManager = new UserManager(); projectManager = new ProjectManager(); } }
Constructor. Initialize global contracts and pointers/
function AdminInterface() { userManager = new UserManager(); projectManager = new ProjectManager(); }
13,112,858
./full_match/3/0x1213164Ae8EAc01051213bC6232f2E3e5f967080/sources/irc.sol
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); }
14,131,638
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../core/Common.sol"; import "../oracle/OracleFacade.sol"; /** * @title Main insurance contract * @dev Implement main contract for Insurance. contract between insurance and farmers is materialized in here * * @notice inhertit {Common} contract */ contract Insurance is Common { /// @dev Emitted when a `contract` is activated by an `insurer` for a given `season` + `region` + `farmID` event InsuranceActivated( uint16 indexed season, bytes32 region, bytes32 farmID, address indexed insurer, bytes32 key ); /// @dev Emitted when a `contract` is submitted by an `farmer` for a given `season` + `region` + `farmID` event InsuranceRequested( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, uint256 fee, address indexed farmer, bytes32 key ); /// @dev Emitted when a `contract` is validated by a `government` for a given `season` + `region` + `farmID` event InsuranceValidated( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 totalStaked, address indexed government, bytes32 key ); /// @dev Emitted when a `contract` is closed without any compensation event InsuranceClosed( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, address indexed farmer, address indexed insurer, address government, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity, bytes32 key ); /// @dev Emitted when a `contract` is closed with any compensation event InsuranceCompensated( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, address indexed farmer, address indexed insurer, address government, uint256 totalStaked, uint256 compensation, Severity severity, bytes32 key ); /// @dev Emitted when an `insurer` withdraws `amount` from the contract. remaining contract balance is `balance` event WithdrawInsurer( address indexed insurer, uint256 amount, uint256 balance ); /** * @dev transition state of a contract * * a contract must be in init state (DEFAULT) * a contract transition to (REGISTERED) once a farmer registers himself * a contract transition to (VALIDATED) once a government employee validates the demand * a contract transition to (INSURED) once an insurer approves the contract * a contract transition to (CLOSED) once a season is closed without any drought, hence there are no compensations * a contract transition to (COMPENSATED) once a season is closed and there were drought, hence there are compensations */ enum ContractState { DEFAULT, REGISTERED, VALIDATED, INSURED, CLOSED, COMPENSATED } struct Contract { bytes32 key; bytes32 farmID; ContractState state; address farmer; address government; address insurer; uint256 size; bytes32 region; uint16 season; uint256 totalStaked; uint256 compensation; uint256 changeGovernment; Severity severity; } /// @dev OracleFacade used to get the status of a season(open/closed) and Severity for a given season + region OracleFacade private oracleFacade; /// @dev a contract is a unique combination between season,region,farmID mapping(bytes32 => Contract) private contracts; /// @dev contracts that must be treated by season,region mapping(bytes32 => bytes32[]) private openContracts; /// @dev contracts that have already been closed by season,region mapping(bytes32 => bytes32[]) private closedContracts; uint256 public constant KEEPER_FEE = 0.01 ether; /// @dev needed to track worst case scenario -> must have at anytime money to pay for severity/D4 : 2.5*PERMIUM_PER_HA*totalsize uint256 public totalOpenSize; /// @dev needed to track amount to be paid for keepers uint256 public totalOpenContracts; /** * @dev rules to calculate the compensation * * D1 gives 0.5 times the premium * D2 gives 1 times the premium * D3 gives 2 times the premium * D4 gives 2.5 times the premium */ mapping(Severity => uint8) private rules; /// @dev premium is 0.15ETH/HA uint256 public constant PERMIUM_PER_HA = 150000000 gwei; /// @dev used for calculation (farmer must stake half of premium. Same for government) uint256 public constant HALF_PERMIUM_PER_HA = 75000000 gwei; /** * @dev Initialize `rules` for compensation. Also setup `gatekeeer` and `oracleFacade` * */ constructor(address _gatekeeper, address _oracleFacade) Common(_gatekeeper) { rules[Severity.D0] = 0; rules[Severity.D1] = 5; rules[Severity.D2] = 10; rules[Severity.D3] = 20; rules[Severity.D4] = 25; oracleFacade = OracleFacade(_oracleFacade); } /// @dev modifier to check that at any time there will be enough balance in the contract modifier minimumCovered() { _; require( address(this).balance >= minimumAmount(), "Not enough balance staked in the contract" ); } /// @dev season must be closed in order to check compensations modifier seasonClosed(uint16 season) { require( oracleFacade.getSeasonState(season) == SeasonState.CLOSED, "Season must be closed." ); _; } /// @dev season must be open in order to receive insurance requests modifier seasonOpen(uint16 season) { require( oracleFacade.getSeasonState(season) == SeasonState.OPEN, "Season must be open." ); _; } /** * @dev retrieve contract data part1 * @param _key keecak combination of season, region & farmID * * @return key unique id of the contract * @return farmID unique ID of a farm * @return state of the contract * @return farmer address * @return government address * @return insurer address * @return size number of HA of a farmer (minimum: 1 HA) */ function getContract1(bytes32 _key) public view returns ( bytes32 key, bytes32 farmID, ContractState state, address farmer, address government, address insurer, uint256 size ) { Contract memory _contract = contracts[_key]; key = _contract.key; farmID = _contract.farmID; state = _contract.state; farmer = _contract.farmer; government = _contract.government; insurer = _contract.insurer; size = _contract.size; } /** * @dev retrieve contract data part2 * @param _key keecak combination of season, region & farmID * * @return region ID of a region * @return season (year) * @return totalStaked eth that were taked in this contract * @return compensation for this contract * @return changeGovernment money returned to government * @return severity Drought severity fetched from oracleFacade when the contract is closed */ function getContract2(bytes32 _key) public view returns ( bytes32 region, uint16 season, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity ) { Contract memory _contract = contracts[_key]; region = _contract.region; season = _contract.season; totalStaked = _contract.totalStaked; compensation = _contract.compensation; changeGovernment = _contract.changeGovernment; severity = _contract.severity; } /** * @dev retrieve contract data (1st part) * @param _season farming season(year) * @param _region region ID * @param _farmID unique ID of a farm * * @return key unique ID of the contract * @return farmID unique ID of a farm * @return state of the contract * @return farmer address * @return government address * @return insurer address * @return size number of HA of a farmer (minimum: 1 HA) */ function getContractData1( uint16 _season, bytes32 _region, bytes32 _farmID ) public view returns ( bytes32 key, bytes32 farmID, ContractState state, address farmer, address government, address insurer, uint256 size ) { (key, farmID, state, farmer, government, insurer, size) = getContract1( getContractKey(_season, _region, _farmID) ); } /** * @dev retrieve contract data (2nd part) * @param _season farming season(year) * @param _region region ID * @param _farmID unique ID of a farm * * @return region ID of a region * @return season (year) * @return totalStaked eth that were taked in this contract * @return compensation for this contract * @return changeGovernment money returned to government * @return severity Drought severity when the contract is closed */ function getContractData2( uint16 _season, bytes32 _region, bytes32 _farmID ) public view returns ( bytes32 region, uint16 season, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity ) { bytes32 _key = getContractKey(_season, _region, _farmID); ( region, season, totalStaked, compensation, changeGovernment, severity ) = getContract2(_key); } /** * @dev get number of closed contracts for a given key * * @param key keccak256 of season + region * @return number of closed contracts * */ function getNumberClosedContractsByKey(bytes32 key) public view returns (uint256) { return closedContracts[key].length; } /** * @dev get number of closed contracts for a given season and region * * @param season id of a season (year) * @param region id of region * @return number of closed contracts * */ function getNumberClosedContracts(uint16 season, bytes32 region) public view returns (uint256) { return getNumberClosedContractsByKey(getSeasonRegionKey(season, region)); } /** * @dev get a specific closed contract * * @param key key keccak256 of season + region * @param index position in the array * @return key of a contract * */ function getClosedContractsAtByKey(bytes32 key, uint256 index) public view returns (bytes32) { require(closedContracts[key].length > index, "Out of bounds access."); return closedContracts[key][index]; } /** * @dev get a specific closed contract * * @param season id of a season (year) * @param region id of region * @param index position in the array * @return key of a contract * */ function getClosedContractsAt( uint16 season, bytes32 region, uint256 index ) public view returns (bytes32) { return getClosedContractsAtByKey( getSeasonRegionKey(season, region), index ); } /** * @dev calculate contract key * * @param season season (year) * @param region region id * @param farmID farm id * @return key (hash value of the 3 parameters) * */ function getContractKey( uint16 season, bytes32 region, bytes32 farmID ) public pure returns (bytes32) { return keccak256(abi.encodePacked(season, region, farmID)); } /** * @dev calculate key of `season`, `region` * * @param season season (year) * @param region region id * @return key (hash value of the 2 parameters) * */ function getSeasonRegionKey(uint16 season, bytes32 region) public pure returns (bytes32) { return keccak256(abi.encodePacked(season, region)); } /** * @dev get number of open contracts for a given key * * @param key keccak256 of season + region * @return number of open contracts * */ function getNumberOpenContractsByKey(bytes32 key) public view returns (uint256) { return openContracts[key].length; } /** * @dev get number of open contracts for a given season and region * * @param season id of a season (year) * @param region id of region * @return number of open contracts * */ function getNumberOpenContracts(uint16 season, bytes32 region) public view returns (uint256) { return getNumberOpenContractsByKey(getSeasonRegionKey(season, region)); } /** * @dev get a specific open contract * * @param key key keccak256 of season + region * @param index position in the array * @return key of a contract * */ function getOpenContractsAtByKey(bytes32 key, uint256 index) public view returns (bytes32) { require(openContracts[key].length > index, "Out of bounds access."); return openContracts[key][index]; } /** * @dev get a specific open contract * * @param season id of a season (year) * @param region id of region * @param index position in the array * @return key of a contract * */ function getOpenContractsAt( uint16 season, bytes32 region, uint256 index ) public view returns (bytes32) { return getOpenContractsAtByKey(getSeasonRegionKey(season, region), index); } /** * @dev insure a request * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * * Emits a {InsuranceActivated} event. * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by insurer * - Check must exist * - Season must be open * - contract must be in VALIDATED state * - Must be enough eth staked within the contract after the operation * @notice call nonReentrant to check against Reentrancy */ function activate( uint16 season, bytes32 region, bytes32 farmID ) external onlyActive onlyInsurer seasonOpen(season) nonReentrant minimumCovered { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); Contract memory _contract = contracts[key]; require(_contract.farmID == farmID, "Contract do not exist"); require( _contract.state == ContractState.VALIDATED, "Contract must be in validated state" ); _contract.state = ContractState.INSURED; _contract.insurer = msg.sender; contracts[key] = _contract; emit InsuranceActivated(season, region, farmID, msg.sender, key); } /** * @dev calculate at anytime the minimum liquidity that must be locked within the contract * * @return ammount * * Basically , always enough money to pay keepers and compensation in worst case scenarios */ function minimumAmount() public view returns (uint256) { return (KEEPER_FEE * totalOpenContracts) + (PERMIUM_PER_HA * totalOpenSize * rules[Severity.D4]) / 10; } /** * @dev submission of an insurance request by a farmer * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * @param size number of HA of a farmer (minimum: 1 HA) * * @return key key of the contract * Emits a {InsuranceRequested} event. * * Requirements: * - contract is Active (circuit-breaker) * - Can only be called by farmer * - Check non duplicate * - Seasonmust be open * - Sender must pay for premium * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function register( uint16 season, bytes32 region, bytes32 farmID, uint256 size ) external payable onlyActive onlyFarmer seasonOpen(season) nonReentrant minimumCovered returns (bytes32) { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); require(contracts[key].key == 0x0, "Duplicate"); uint256 fee = HALF_PERMIUM_PER_HA * size; require(msg.value >= fee, "Not enough money to pay for premium"); Contract memory _contract; _contract.key = key; _contract.farmID = farmID; _contract.state = ContractState.REGISTERED; _contract.farmer = msg.sender; _contract.size = size; _contract.region = region; _contract.season = season; _contract.totalStaked = fee; contracts[key] = _contract; openContracts[getSeasonRegionKey(season, region)].push(key); totalOpenSize += size; totalOpenContracts++; // return change if (msg.value > fee) { (bool success, ) = msg.sender.call{value: msg.value - fee}(""); require(success, "Transfer failed."); } emit InsuranceRequested( season, region, farmID, size, fee, msg.sender, key ); return key; } /** * @dev validate a request done by a farmer * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * * Emits a {InsuranceValidated} event. * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by government * - Check contract must exist * - Season must be open * - Sender must pay for premium * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function validate( uint16 season, bytes32 region, bytes32 farmID ) external payable onlyActive onlyGovernment seasonOpen(season) nonReentrant minimumCovered { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); Contract memory _contract = contracts[key]; require(_contract.farmID == farmID, "Contract do not exist"); require( _contract.state == ContractState.REGISTERED, "Contract must be in registered state" ); uint256 fee = HALF_PERMIUM_PER_HA * _contract.size; require(msg.value >= fee, "Not enough money to pay for premium"); _contract.state = ContractState.VALIDATED; _contract.government = msg.sender; _contract.totalStaked += fee; contracts[key] = _contract; // return change if (msg.value > fee) { (bool success, ) = msg.sender.call{value: msg.value - fee}(""); require(success, "Transfer failed."); } emit InsuranceValidated( season, region, farmID, _contract.totalStaked, msg.sender, key ); } /** * @dev process an insurance file. triggered by a `keeper` * @dev as a combination of `season`,`region` can have several open insurances files, a keeper will have to loop over this function until there are no more open insurances files. looping is done offchain rather than onchain in order to avoid any out of gas exception * @param season farming season(year) * @param region region ID * * Emits a {InsuranceClosed} event in case an insurance file has been closed without any compensation (e.g.: Drought severity <= D1) or returned back becase government has not staked 1/2 of the premium * Emits a {InsuranceCompensated} event in case an insurance file has been processed with compensation (e.g.: Drought severity >= D2) * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by keeper * - Check contract must exist * - Season must be closed * - Must be open contracts to process * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function process(uint16 season, bytes32 region) external onlyActive onlyKeeper seasonClosed(season) nonReentrant minimumCovered { bytes32 seasonRegionKey = getSeasonRegionKey(season, region); bytes32[] memory _openContracts = openContracts[seasonRegionKey]; require( _openContracts.length > 0, "No open insurance contracts to process for this season,region" ); Severity severity = oracleFacade.getRegionSeverity(season, region); uint256 numberSubmissions = oracleFacade.getSubmissionTotal( season, region ); require( !((numberSubmissions > 0) && (severity == Severity.D)), "Severity has not been aggregated yet" ); // get last element bytes32 key = _openContracts[_openContracts.length - 1]; Contract memory _contract = contracts[key]; _contract.severity = severity; Contract memory newContract = _process(_contract); // Update internal state openContracts[seasonRegionKey].pop(); closedContracts[seasonRegionKey].push(key); contracts[key] = newContract; totalOpenSize -= newContract.size; totalOpenContracts--; // pay back if (newContract.compensation > 0) { _deposit(newContract.farmer, newContract.compensation); } if (newContract.changeGovernment > 0) { _deposit(newContract.government, newContract.changeGovernment); } // pay keeper for its work _deposit(msg.sender, KEEPER_FEE); // emit events if (newContract.state == ContractState.COMPENSATED) { emit InsuranceCompensated( newContract.season, newContract.region, newContract.farmID, newContract.size, newContract.farmer, newContract.insurer, newContract.government, newContract.totalStaked, newContract.compensation, newContract.severity, newContract.key ); } else { emit InsuranceClosed( newContract.season, newContract.region, newContract.farmID, newContract.size, newContract.farmer, newContract.insurer, newContract.government, newContract.totalStaked, newContract.compensation, newContract.changeGovernment, newContract.severity, newContract.key ); } } /** * @dev private function to calculate the new version of the insurance contract after processing * @param _contract current contract before processing * @return newContract new contract after processing * */ function _process(Contract memory _contract) private view returns (Contract memory newContract) { bool isCompensated = false; newContract = _contract; if (newContract.state == ContractState.INSURED) { if (newContract.severity == Severity.D0) { // no compensation if D0 newContract.compensation = 0; newContract.changeGovernment = 0; } else if (newContract.severity == Severity.D) { // if season closed but oracles didn't do their job by providing data then return the change newContract.compensation = newContract.totalStaked / 2; newContract.changeGovernment = newContract.totalStaked / 2; } else { isCompensated = true; // calculate compensation newContract.compensation = (rules[newContract.severity] * newContract.totalStaked) / 10; newContract.changeGovernment = 0; } } else if (newContract.state == ContractState.REGISTERED) { // return money back if season closed validation before approval of government newContract.compensation = newContract.totalStaked; } else if (newContract.state == ContractState.VALIDATED) { newContract.compensation = newContract.totalStaked / 2; newContract.changeGovernment = newContract.totalStaked / 2; } //Update contract state if (isCompensated) { newContract.state = ContractState.COMPENSATED; } else { newContract.state = ContractState.CLOSED; } } /** * @dev an insurer can withdraw any excess of liquidity * @param amount to be withdrawed * * Emits a {WithdrawInsurer} event. * * Requirements: * - Can only be called by insurer * - Check non duplicate * - Must be enough eth staked within the contract after operation * @notice call nonReentrant to check against Reentrancy */ function withdrawInsurer(uint256 amount) external onlyInsurer nonReentrant minimumCovered { require( address(this).balance >= amount, "Not enough balance in the contract" ); (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed."); emit WithdrawInsurer(msg.sender, amount, address(this).balance); } /** * @dev check anytime amount that can be withdrawed by insurer * @return amount to be withdrawed * * @notice call nonReentrant to check against Reentrancy */ function withdrawableInsurer() external view returns (uint256) { uint256 minimum = minimumAmount(); if (address(this).balance >= minimum) { return address(this).balance - minimum; } else { return 0; } } /** * @dev function to receive ETH in order to pay keepers and oracles * * Emits a {ReceivedETH} event. * * Requirements: * - Contract mus be active (circuit-breaker) * - the caller must be insurer */ receive() external payable onlyActive onlyInsurer { emit ReceivedETH(msg.value, address(this).balance, msg.sender); } }
get a specific closed contract season id of a season (year) region id of region index position in the array return key of a contract/
function getClosedContractsAt( uint16 season, bytes32 region, uint256 index ) public view returns (bytes32) { return getClosedContractsAtByKey( getSeasonRegionKey(season, region), index ); }
13,043,458
./full_match/5/0xC89511CFB3e8cbAA9470a9fE50184EAF7204c175/sources/contracts/TFOP.sol
is burning really needed? Burning changes the total supply and changing total supply affects minting logic... Burn the NFT tokens/
function burnNFT(uint256 tokenId) public { require( ownerOf(tokenId) == msg.sender, "Only token owner can burn thier NFTs" ); _burn(tokenId); }
1,899,966
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "@nomiclabs/buidler/console.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IUniswapV2Pair } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import { IUniswapV2Factory } from "./lib/IUniswapV2Factory.sol"; import { IReferee } from "./interface/IReferee.sol"; import { Bitcoin } from "./types/Bitcoin.sol"; import { Option } from "./Option.sol"; import { IOption } from "./interface/IOption.sol"; import { Obligation } from "./Obligation.sol"; import { IObligation } from "./interface/IObligation.sol"; import { IOptionPairFactory } from "./interface/IOptionPairFactory.sol"; import { Treasury } from "./Treasury.sol"; import { ITreasury } from "./interface/ITreasury.sol"; /// @title Parent Factory /// @author Interlay /// @notice Tracks and manages ERC20 Option pairs. contract OptionPairFactory is IOptionPairFactory { using SafeMath for uint256; string constant ERR_INVALID_OPTION = "Option does not exist"; string constant ERR_ZERO_AMOUNT = "Requires non-zero amount"; string constant ERR_NO_BTC_ADDRESS = "Insurer lacks BTC address"; /// @notice Emitted whenever this factory creates a new option pair. event Create(address indexed option, address indexed obligation, uint256 expiryTime, uint256 windowSize, uint256 strikePrice); mapping(address => address) public getObligation; mapping(address => address) public getTreasury; mapping(address => address) public getCollateral; address[] public options; mapping (address => Bitcoin.Address) internal _btcAddresses; /** * @notice Sets the preferred payout address for the caller. * * The script format is defined by the `Bitcoin.Script` enum which describes * the expected output format (P2SH, P2PKH, P2WPKH). * * @param btcHash Address hash * @param format Payment format **/ function setBtcAddress(bytes20 btcHash, Bitcoin.Script format) external override { require( btcHash != 0, ERR_NO_BTC_ADDRESS ); _btcAddresses[msg.sender].btcHash = btcHash; _btcAddresses[msg.sender].format = format; } /** * @notice Get the preferred BTC address for the caller. * @return btcHash Address hash * @return format Payment format **/ function getBtcAddress() external override view returns (bytes20 btcHash, Bitcoin.Script format) { return (_btcAddresses[msg.sender].btcHash, _btcAddresses[msg.sender].format); } function _createOption( uint256 expiryTime, uint256 windowSize, address referee, address treasury, address obligation, bytes32 salt ) internal returns (address option) { bytes memory bytecode = type(Option).creationCode; assembly { // solium-disable-previous-line security/no-inline-assembly option := create2(0, add(bytecode, 32), mload(bytecode), salt) } IOption(option).initialize( expiryTime, windowSize, referee, treasury, obligation ); return option; } function _createObligation( uint256 expiryTime, uint256 windowSize, uint256 strikePrice, address treasury, bytes32 salt ) internal returns (address obligation) { bytes memory bytecode = type(Obligation).creationCode; assembly { // solium-disable-previous-line security/no-inline-assembly obligation := create2(0, add(bytecode, 32), mload(bytecode), salt) } IObligation(obligation).initialize( expiryTime, windowSize, strikePrice, treasury ); return obligation; } /** * @notice Creates a new option pair with the given parameters. If no * treasury contract exists for the associated collateral address a new one * is made and registered. The ownership of the obligation-side contract is * immediately transferred to the option-side contract. * @param expiryTime Unix expiry date * @param windowSize Settlement window * @param strikePrice Strike price * @param collateral Backing currency * @param referee Underlying settlement **/ function createPair( uint256 expiryTime, uint256 windowSize, uint256 strikePrice, address collateral, address referee ) external override returns (address option, address obligation) { address treasury = getTreasury[collateral]; if (treasury == address(0)) { treasury = address(new Treasury(collateral)); } bytes32 salt = keccak256(abi.encodePacked( expiryTime, windowSize, strikePrice, collateral, referee )); obligation = _createObligation(expiryTime, windowSize, strikePrice, treasury, salt); option = _createOption(expiryTime, windowSize, referee, treasury, obligation, salt); Ownable(obligation).transferOwnership(option); getObligation[option] = obligation; getTreasury[collateral] = treasury; getCollateral[option] = collateral; options.push(option); emit Create(option, obligation, expiryTime, windowSize, strikePrice); } }
Creates a new option pair with the given parameters. If no treasury contract exists for the associated collateral address a new one is made and registered. The ownership of the obligation-side contract is immediately transferred to the option-side contract. expiryTime Unix expiry date windowSize Settlement window strikePrice Strike price collateral Backing currency referee Underlying settlement/
function createPair( uint256 expiryTime, uint256 windowSize, uint256 strikePrice, address collateral, address referee ) external override returns (address option, address obligation) { address treasury = getTreasury[collateral]; if (treasury == address(0)) { treasury = address(new Treasury(collateral)); } bytes32 salt = keccak256(abi.encodePacked( expiryTime, windowSize, strikePrice, collateral, referee )); obligation = _createObligation(expiryTime, windowSize, strikePrice, treasury, salt); option = _createOption(expiryTime, windowSize, referee, treasury, obligation, salt); Ownable(obligation).transferOwnership(option); getObligation[option] = obligation; getTreasury[collateral] = treasury; getCollateral[option] = collateral; options.push(option); emit Create(option, obligation, expiryTime, windowSize, strikePrice); }
12,561,679
// File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol 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; } } // File: ether-library/contracts/IERC20.sol pragma solidity >=0.4.0; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the erc20 token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // 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: ether-library/contracts/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using 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/StakingInitializable.sol pragma solidity 0.6.12; contract StakingInitializable is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The address of the staking factory address public STAKING_FACTORY; // Whether a limit is set for users bool public hasUserLimit; // Whether it is initialized bool public isInitialized; // Accrued token per share uint256 public accTokenPerShare; // The block number when reward ends. uint256 public endBlock; // The block number when reward starts. uint256 public startBlock; // The block number of the last pool update uint256 public lastRewardBlock; // The deposit fee uint16 public depositFee; // The withdraw fee when stake before the locked time uint16 public withdrawFee; // The withdraw lock period uint256 public lockPeriod; // The fee address address payable public feeAddress; // The pool limit (0 if none) uint256 public poolLimitPerUser; // reward tokens created per block. uint256 public rewardPerBlock; uint16 public constant MAX_DEPOSIT_FEE = 2000; uint16 public constant MAX_WITHDRAW_FEE = 2000; uint256 public constant MAX_LOCK_PERIOD = 30 days; uint256 public constant MAX_EMISSION_RATE = 10**7; // The precision factor uint256 public PRECISION_FACTOR; // The reward token IERC20 public rewardToken; // The staked token IERC20 public stakedToken; // Total supply of staked token uint256 public stakedSupply; // Info of each user that stakes tokens (stakedToken) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // How many staked tokens the user has provided uint256 rewardDebt; // Reward debt uint256 lastDepositedAt; // Last deposited time } event AdminTokenRecovery(address tokenRecovered, uint256 amount); event UserDeposited(address indexed user, uint256 amount); event EmergencyWithdrawn(address indexed user, uint256 amount); event EmergencyRewardWithdrawn(uint256 amount); event StartAndEndBlocksUpdated(uint256 startBlock, uint256 endBlock); event RewardPerBlockUpdated(uint256 oldValue, uint256 newValue); event DepositFeeUpdated(uint16 oldValue, uint16 newValue); event WithdrawFeeUpdated(uint16 oldValue, uint16 newValue); event LockPeriodUpdated(uint256 oldValue, uint256 newValue); event FeeAddressUpdated(address oldAddress, address newAddress); event PoolLimitUpdated(uint256 oldValue, uint256 newValue); event RewardsStopped(uint256 blockNumber); event UserWithdrawn(address indexed user, uint256 amount); constructor() public { STAKING_FACTORY = msg.sender; } /** * @notice Initialize the contract * @param _stakedToken: staked token address * @param _rewardToken: reward token address * @param _rewardPerBlock: reward per block (in rewardToken) * @param _startBlock: start block * @param _endBlock: end block * @param _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0) * @param _depositFee: deposit fee * @param _withdrawFee: withdraw fee * @param _lockPeriod: lock period * @param _feeAddress: fee address * @param _admin: admin address with ownership */ function initialize( IERC20 _stakedToken, IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock, uint256 _poolLimitPerUser, uint16 _depositFee, uint16 _withdrawFee, uint256 _lockPeriod, address payable _feeAddress, address _admin ) external { require(!isInitialized, "Already initialized"); require(msg.sender == STAKING_FACTORY, "Not factory"); require(_stakedToken.totalSupply() >= 0, "Invalid stake token"); require(_rewardToken.totalSupply() >= 0, "Invalid reward token"); require(_feeAddress != address(0), "Invalid zero address"); _stakedToken.balanceOf(address(this)); _rewardToken.balanceOf(address(this)); // require(_stakedToken != _rewardToken, "stakedToken must be different from rewardToken"); require(_startBlock > block.number, "startBlock cannot be in the past"); require( _startBlock < _endBlock, "startBlock must be lower than endBlock" ); // Make this contract initialized isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; require(_depositFee <= MAX_DEPOSIT_FEE, "Invalid deposit fee"); depositFee = _depositFee; require(_withdrawFee <= MAX_WITHDRAW_FEE, "Invalid withdraw fee"); withdrawFee = _withdrawFee; require(_lockPeriod <= MAX_LOCK_PERIOD, "Invalid lock period"); lockPeriod = _lockPeriod; feeAddress = _feeAddress; if (_poolLimitPerUser > 0) { hasUserLimit = true; poolLimitPerUser = _poolLimitPerUser; } uint256 decimalsRewardToken = uint256(rewardToken.decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken))); // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; // Transfer ownership to the admin address who becomes owner of the contract transferOwnership(_admin); } /* * @notice Deposit staked tokens and collect reward tokens (if any) * @param _amount: amount to withdraw (in rewardToken) */ function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; if (hasUserLimit) { require( _amount.add(user.amount) <= poolLimitPerUser, "User amount above limit" ); } _updatePool(); if (user.amount > 0) { uint256 pending = user .amount .mul(accTokenPerShare) .div(PRECISION_FACTOR) .sub(user.rewardDebt); if (pending > 0) { safeRewardTransfer(msg.sender, pending); } } if (_amount > 0) { uint256 balanceBefore = stakedToken.balanceOf(address(this)); stakedToken.safeTransferFrom(msg.sender, address(this), _amount); _amount = stakedToken.balanceOf(address(this)).sub(balanceBefore); uint256 feeAmount = 0; if (depositFee > 0) { feeAmount = _amount.mul(depositFee).div(10000); if (feeAmount > 0) { stakedToken.safeTransfer(feeAddress, feeAmount); } } user.amount = user.amount.add(_amount).sub(feeAmount); user.lastDepositedAt = block.timestamp; stakedSupply = stakedSupply.add(_amount).sub(feeAmount); } user.rewardDebt = user.amount.mul(accTokenPerShare).div( PRECISION_FACTOR ); emit UserDeposited(msg.sender, _amount); } /* * @notice Withdraw staked tokens and collect reward tokens * @param _amount: amount to withdraw (in rewardToken) */ function withdraw(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; require( stakedSupply >= _amount && user.amount >= _amount, "Amount to withdraw too high" ); _updatePool(); uint256 pending = user .amount .mul(accTokenPerShare) .div(PRECISION_FACTOR) .sub(user.rewardDebt); if (_amount > 0) { user.amount = user.amount.sub(_amount); stakedSupply = stakedSupply.sub(_amount); // Check if lock period passed if (user.lastDepositedAt.add(lockPeriod) > block.timestamp) { uint256 feeAmount = _amount.mul(withdrawFee).div(10000); if (feeAmount > 0) { _amount = _amount.sub(feeAmount); stakedToken.safeTransfer(feeAddress, feeAmount); } } if (_amount > 0) { stakedToken.safeTransfer(msg.sender, _amount); } } if (pending > 0) { safeRewardTransfer(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div( PRECISION_FACTOR ); emit UserWithdrawn(msg.sender, _amount); } /** * @notice Safe reward transfer, just in case if rounding error causes pool to not have enough reward tokens. * @param _to receiver address * @param _amount amount to transfer * @return realAmount amount sent to the receiver */ function safeRewardTransfer(address _to, uint256 _amount) internal returns (uint256 realAmount) { uint256 rewardBalance = rewardToken.balanceOf(address(this)); if (_amount > 0 && rewardBalance > 0) { realAmount = _amount; // When there is not enough reward balance, just send available rewards if (realAmount > rewardBalance) { realAmount = rewardBalance; } // When staked token is same as reward token, rewarding amount should not occupy staked amount if ( address(stakedToken) != address(rewardToken) || stakedSupply.add(realAmount) <= rewardBalance ) { rewardToken.safeTransfer(_to, realAmount); } else if (stakedSupply < rewardBalance) { realAmount = rewardBalance.sub(stakedSupply); rewardToken.safeTransfer(_to, realAmount); } else { realAmount = 0; } } else { realAmount = 0; } return realAmount; } /** * @notice Withdraw staked tokens without caring about rewards rewards * @dev Needs to be for emergency. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 amountToTransfer = user.amount; user.amount = 0; user.rewardDebt = 0; stakedSupply = stakedSupply.sub(amountToTransfer); if (amountToTransfer > 0) { stakedToken.safeTransfer(msg.sender, amountToTransfer); } emit EmergencyWithdrawn(msg.sender, amountToTransfer); } /** * @notice Withdraw all reward tokens * @dev Only callable by owner. Needs to be for emergency. */ function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { require( startBlock > block.number || endBlock < block.number, "Not allowed to remove reward tokens while pool is live" ); safeRewardTransfer(msg.sender, _amount); emit EmergencyRewardWithdrawn(_amount); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require( _tokenAddress != address(stakedToken), "Cannot be staked token" ); require( _tokenAddress != address(rewardToken), "Cannot be reward token" ); IERC20(_tokenAddress).safeTransfer(msg.sender, _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /* * @notice Stop rewards * @dev Only callable by owner */ function stopReward() external onlyOwner { require(startBlock < block.number, "Pool has not started"); require(block.number <= endBlock, "Pool has ended"); endBlock = block.number; emit RewardsStopped(block.number); } /* * @notice Update pool limit per user * @dev Only callable by owner. * @param _hasUserLimit: whether the limit remains forced * @param _poolLimitPerUser: new pool limit per user */ function updatePoolLimitPerUser( bool _hasUserLimit, uint256 _poolLimitPerUser ) external onlyOwner { require(hasUserLimit, "Must be set"); uint256 oldValue = poolLimitPerUser; if (_hasUserLimit) { require( _poolLimitPerUser > poolLimitPerUser, "New limit must be higher" ); poolLimitPerUser = _poolLimitPerUser; } else { hasUserLimit = _hasUserLimit; poolLimitPerUser = 0; } emit PoolLimitUpdated(oldValue, _poolLimitPerUser); } /* * @notice Update reward per block * @dev Only callable by owner. * @param _rewardPerBlock: the reward per block */ function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { require(rewardPerBlock != _rewardPerBlock, "Same value alrady set"); uint256 rewardDecimals = uint256(rewardToken.decimals()); require( _rewardPerBlock <= MAX_EMISSION_RATE.mul(10**rewardDecimals), "Out of maximum emission rate" ); _updatePool(); emit RewardPerBlockUpdated(rewardPerBlock, _rewardPerBlock); rewardPerBlock = _rewardPerBlock; } /* * @notice Update deposit fee * @dev Only callable by owner. * @param _depositFee: the deposit fee */ function updateDepositFee(uint16 _depositFee) external onlyOwner { require(depositFee != _depositFee, "Same vaue already set"); require(_depositFee <= MAX_DEPOSIT_FEE, "Invalid deposit fee"); emit DepositFeeUpdated(depositFee, _depositFee); depositFee = _depositFee; } /* * @notice Update withdraw fee * @dev Only callable by owner. * @param _withdrawFee: the deposit fee */ function updateWithdrawFee(uint16 _withdrawFee) external onlyOwner { require(withdrawFee != _withdrawFee, "Same value already set"); require(_withdrawFee <= MAX_WITHDRAW_FEE, "Invalid withdraw fee"); emit WithdrawFeeUpdated(withdrawFee, _withdrawFee); withdrawFee = _withdrawFee; } /* * @notice Update withdraw lock period * @dev Only callable by owner. * @param _lockPeriod: the withdraw lock period */ function updateLockPeriod(uint256 _lockPeriod) external onlyOwner { require(lockPeriod != _lockPeriod, "Same value already set"); require(_lockPeriod <= MAX_LOCK_PERIOD, "Exceeds max lock period"); emit LockPeriodUpdated(lockPeriod, _lockPeriod); lockPeriod = _lockPeriod; } /* * @notice Update fee address * @dev Only callable by owner. * @param _feeAddress: the fee address */ function updateFeeAddress(address _feeAddress) external onlyOwner { require(_feeAddress != address(0), "Invalid zero address"); require(feeAddress != _feeAddress, "Same value already set"); require(feeAddress != _feeAddress, "Same fee address already set"); emit FeeAddressUpdated(feeAddress, _feeAddress); feeAddress = payable(_feeAddress); } /** * @notice It allows the admin to update start and end blocks * @dev This function is only callable by owner. * @param _startBlock: the new start block * @param _endBlock: the new end block */ function updateStartAndEndBlocks(uint256 _startBlock, uint256 _endBlock) external onlyOwner { require(block.number < startBlock, "Pool has started"); require( _startBlock < _endBlock, "New startBlock must be lower than new endBlock" ); require( block.number < _startBlock, "New startBlock must be higher than current block" ); startBlock = _startBlock; endBlock = _endBlock; // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; emit StartAndEndBlocksUpdated(_startBlock, _endBlock); } /* * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; if (block.number > lastRewardBlock && stakedSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 rewardAmount = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add( rewardAmount.mul(PRECISION_FACTOR).div(stakedSupply) ); return user .amount .mul(adjustedTokenPerShare) .div(PRECISION_FACTOR) .sub(user.rewardDebt); } else { return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub( user.rewardDebt ); } } /* * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } if (stakedSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 rewardAmount = multiplier.mul(rewardPerBlock); accTokenPerShare = accTokenPerShare.add( rewardAmount.mul(PRECISION_FACTOR).div(stakedSupply) ); lastRewardBlock = block.number; } /* * @notice Return reward multiplier over the given _from to _to block. * @param _from: block to start * @param _to: block to finish */ function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_to <= endBlock) { return _to.sub(_from); } else if (_from >= endBlock) { return 0; } else { return endBlock.sub(_from); } } }
Update reward variables of the given pool to be up-to-date./
function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } if (stakedSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 rewardAmount = multiplier.mul(rewardPerBlock); accTokenPerShare = accTokenPerShare.add( rewardAmount.mul(PRECISION_FACTOR).div(stakedSupply) ); lastRewardBlock = block.number; }
1,644,159
./full_match/80001/0x07c7D97B7c07192555FA813dE4da54285A182F84/sources/project_/contracts/interfaces/ISubscriptionManager.sol
Must only be called by a subscription contract
function recordSubscriptionPayment(address _subscriber) external;
840,246
// SPDX-License-Identifier: MIT pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; import {IGelatoCore, TaskReceipt} from "../gelato_core/interfaces/IGelatoCore.sol"; import {IGelatoProviders} from "../gelato_core/interfaces/IGelatoProviders.sol"; import {IGelatoExecutors} from "../gelato_core/interfaces/IGelatoExecutors.sol"; import {IGelatoSysAdmin} from "../gelato_core/interfaces/IGelatoSysAdmin.sol"; import {Address} from "../external/Address.sol"; import {GelatoTaskReceipt} from "../libraries/GelatoTaskReceipt.sol"; import {GelatoString} from "../libraries/GelatoString.sol"; /// @title PermissionedExecutors /// @notice Contract that masks 2 known executor addresses behind one address /// @author gitpusha & HilmarX contract PermissionedExecutors { using Address for address payable; using GelatoTaskReceipt for TaskReceipt; using GelatoString for string; struct Reponse { uint256 taskReceiptId; uint256 taskGasLimit; string response; } address public immutable gelatoCore; address public constant first_executor = 0x4d671CD743027fB5Af1b2D2a3ccbafA97b5B1B80; address public constant second_executor = 0x99E69499973484a96639f4Fb17893BC96000b3b8; constructor(address _gelatoCore) public payable { gelatoCore = _gelatoCore; if (msg.value >= IGelatoSysAdmin(_gelatoCore).minExecutorStake()) IGelatoExecutors(_gelatoCore).stakeExecutor{value: msg.value}(); } /// @dev needed for unstaking/withdrawing from GelatoCore receive() external payable { require(msg.sender == gelatoCore, "PermissionedExecutors.receive"); } modifier onlyExecutors { require( msg.sender == first_executor || msg.sender == second_executor, "PermissionedExecutors.onlyExecutor" ); _; } function stakeExecutor() public payable virtual { IGelatoExecutors(gelatoCore).stakeExecutor{value: msg.value}(); } function unstakeExecutor() public virtual onlyExecutors { uint256 stake = IGelatoProviders(gelatoCore).executorStake(address(this)); IGelatoExecutors(gelatoCore).unstakeExecutor(); msg.sender.sendValue(stake); } function withdrawExcessExecutorStake(uint256 _withdrawAmount) public payable virtual onlyExecutors { msg.sender.sendValue( IGelatoExecutors(gelatoCore).withdrawExcessExecutorStake(_withdrawAmount) ); } /// @dev This aggregates results and saves network provider requests function multiCanExec(TaskReceipt[] memory _TRs, uint256 _gelatoGasPrice) public view virtual returns (uint256 blockNumber, Reponse[] memory responses) { blockNumber = block.number; uint256 gelatoMaxGas = IGelatoSysAdmin(gelatoCore).gelatoMaxGas(); responses = new Reponse[](_TRs.length); for(uint256 i = 0; i < _TRs.length; i++) { uint256 taskGasLimit = getGasLimit(_TRs[i], gelatoMaxGas); try IGelatoCore(gelatoCore).canExec( _TRs[i], taskGasLimit, _gelatoGasPrice ) returns(string memory response) { responses[i] = Reponse({ taskReceiptId: _TRs[i].id, taskGasLimit: taskGasLimit, response: response }); } catch { responses[i] = Reponse({ taskReceiptId: _TRs[i].id, taskGasLimit: taskGasLimit, response: "PermissionedExecutors.multiCanExec: failed" }); } } } /// @notice only the hardcoded Executors can call this /// @dev Caution: there is no built-in coordination mechanism between the 2 /// Executors. Only one Executor should be live at all times, lest they /// will incur tx collision costs. function exec(TaskReceipt calldata _TR) public virtual onlyExecutors { try IGelatoCore(gelatoCore).exec(_TR) { } catch Error(string memory error) { error.revertWithInfo("PermissionedExecutors.exec:"); } catch { revert("PermissionedExecutors.exec:unknown error"); } } function multiReassignProviders(address[] calldata _providers, address _newExecutor) public virtual onlyExecutors { IGelatoExecutors(gelatoCore).multiReassignProviders(_providers, _newExecutor); } function getGasLimit(TaskReceipt memory _TR, uint256 _gelatoMaxGas) public pure virtual returns(uint256) { if (_TR.selfProvider()) return _TR.task().selfProviderGasLimit; return _gelatoMaxGas; } }
This aggregates results and saves network provider requests
function multiCanExec(TaskReceipt[] memory _TRs, uint256 _gelatoGasPrice) public view virtual returns (uint256 blockNumber, Reponse[] memory responses) { blockNumber = block.number; uint256 gelatoMaxGas = IGelatoSysAdmin(gelatoCore).gelatoMaxGas(); responses = new Reponse[](_TRs.length); for(uint256 i = 0; i < _TRs.length; i++) { uint256 taskGasLimit = getGasLimit(_TRs[i], gelatoMaxGas); try IGelatoCore(gelatoCore).canExec( _TRs[i], taskGasLimit, _gelatoGasPrice ) returns(string memory response) { responses[i] = Reponse({ taskReceiptId: _TRs[i].id, taskGasLimit: taskGasLimit, response: response }); responses[i] = Reponse({ taskReceiptId: _TRs[i].id, taskGasLimit: taskGasLimit, response: "PermissionedExecutors.multiCanExec: failed" }); } } }
5,440,941
./full_match/1/0xBc38243f07cac820dcE26Dd70B82D45D34C8da24/sources/contracts/pool/metadata/MetadataGenerator.sol
escape characters in SVG that need to be HTML escaped & becomes &amp; ' becomes &apos; " becomes &quot; < becomes &lt; > becomes &gt; charCode the character code to escape return needsEscape whether the character needs to be escaped return escapeString the string to replace the character with/
function _escapeCharacterCode(bytes1 charCode) private pure returns (bool needsEscape, string memory escapeString) { if (charCode == 0x26) { return (true, "&amp;"); return (true, "&apos;"); return (true, "&quot;"); return (true, "&lt;"); return (true, "&gt;"); return (false, ""); } }
4,828,498
pragma solidity 0.6.8; library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } interface ERC20 { function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint value) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); function approve(address spender, uint value) external returns (bool success); } contract yRiseTokenSale { using SafeMath for uint256; uint256 public totalSold; ERC20 public yRiseToken; address payable public owner; uint256 public collectedETH; uint256 public startDate; bool public softCapMet; bool private presaleClosed = false; uint256 private ethWithdrawals = 0; uint256 private lastWithdrawal; // tracks all contributors. mapping(address => uint256) internal _contributions; // adjusts for different conversion rates. mapping(address => uint256) internal _averagePurchaseRate; // total contributions from wallet. mapping(address => uint256) internal _numberOfContributions; constructor(address _wallet) public { owner = msg.sender; yRiseToken = ERC20(_wallet); } uint256 amount; uint256 rateDay1 = 20; uint256 rateDay2 = 16; uint256 rateDay3 = 13; uint256 rateDay4 = 10; uint256 rateDay5 = 8; // Converts ETH to yRise and sends new yRise to the sender receive () external payable { require(startDate > 0 && now.sub(startDate) <= 7 days); require(yRiseToken.balanceOf(address(this)) > 0); require(msg.value >= 0.1 ether && msg.value <= 3 ether); require(!presaleClosed); if (now.sub(startDate) <= 1 days) { amount = msg.value.mul(20); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay1.mul(10)); } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) { amount = msg.value.mul(16); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay2.mul(10)); } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) { amount = msg.value.mul(13); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay3.mul(10)); } else if(now.sub(startDate) > 3 days && now.sub(startDate) <= 4 days) { amount = msg.value.mul(10); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay4.mul(10)); } else if(now.sub(startDate) > 4 days) { amount = msg.value.mul(8); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay5.mul(10)); } require(amount <= yRiseToken.balanceOf(address(this))); // update constants. totalSold = totalSold.add(amount); collectedETH = collectedETH.add(msg.value); // update address contribution + total contributions. _contributions[msg.sender] = _contributions[msg.sender].add(amount); _numberOfContributions[msg.sender] = _numberOfContributions[msg.sender].add(1); // transfer the tokens. yRiseToken.transfer(msg.sender, amount); // check if soft cap is met. if (!softCapMet && collectedETH >= 100 ether) { softCapMet = true; } } // Converts ETH to yRise and sends new yRise to the sender function contribute() external payable { require(startDate > 0 && now.sub(startDate) <= 7 days); require(yRiseToken.balanceOf(address(this)) > 0); require(msg.value >= 0.1 ether && msg.value <= 3 ether); require(!presaleClosed); if (now.sub(startDate) <= 1 days) { amount = msg.value.mul(20); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay1.mul(10)); } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) { amount = msg.value.mul(16); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay2.mul(10)); } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) { amount = msg.value.mul(13); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay3.mul(10)); } else if(now.sub(startDate) > 3 days && now.sub(startDate) <= 4 days) { amount = msg.value.mul(10); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay4.mul(10)); } else if(now.sub(startDate) > 4 days) { amount = msg.value.mul(8); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay5.mul(10)); } require(amount <= yRiseToken.balanceOf(address(this))); // update constants. totalSold = totalSold.add(amount); collectedETH = collectedETH.add(msg.value); // update address contribution + total contributions. _contributions[msg.sender] = _contributions[msg.sender].add(amount); _numberOfContributions[msg.sender] = _numberOfContributions[msg.sender].add(1); // transfer the tokens. yRiseToken.transfer(msg.sender, amount); // check if soft cap is met. if (!softCapMet && collectedETH >= 100 ether) { softCapMet = true; } } function numberOfContributions(address from) public view returns(uint256) { return _numberOfContributions[address(from)]; } function contributions(address from) public view returns(uint256) { return _contributions[address(from)]; } function averagePurchaseRate(address from) public view returns(uint256) { return _averagePurchaseRate[address(from)]; } // if the soft cap isn't met and the presale period ends (7 days) enable // users to buy back their ether. function buyBackETH(address payable from) public { require(now.sub(startDate) > 7 days && !softCapMet); require(_contributions[from] > 0); uint256 exchangeRate = _averagePurchaseRate[from].div(10).div(_numberOfContributions[from]); uint256 contribution = _contributions[from]; // remove funds from users contributions. _contributions[from] = 0; // transfer funds back to user. from.transfer(contribution.div(exchangeRate)); } // Function to withdraw raised ETH (staggered withdrawals) // Only the contract owner can call this function function withdrawETH() public { require(msg.sender == owner && address(this).balance > 0); require(softCapMet == true && presaleClosed == true); uint256 withdrawAmount; // first ether withdrawal (max 150 ETH) if (ethWithdrawals == 0) { if (collectedETH <= 150 ether) { withdrawAmount = collectedETH; } else { withdrawAmount = 150 ether; } } else { // remaining ether withdrawal (max 150 ETH per withdrawal) // staggered in 7 day periods. uint256 currDate = now; // ensure that it has been at least 7 days. require(currDate.sub(lastWithdrawal) >= 7 days); if (collectedETH <= 150 ether) { withdrawAmount = collectedETH; } else { withdrawAmount = 150 ether; } } lastWithdrawal = now; ethWithdrawals = ethWithdrawals.add(1); collectedETH = collectedETH.sub(withdrawAmount); owner.transfer(withdrawAmount); } function endPresale() public { require(msg.sender == owner); presaleClosed = true; } // Function to burn remaining yRise (sale must be over to call) // Only the contract owner can call this function function burnyRise() public { require(msg.sender == owner && yRiseToken.balanceOf(address(this)) > 0 && now.sub(startDate) > 7 days); // burn the left over. yRiseToken.transfer(address(0), yRiseToken.balanceOf(address(this))); } //Starts the sale //Only the contract owner can call this function function startSale() public { require(msg.sender == owner && startDate==0); startDate=now; } //Function to query the supply of yRise in the contract function availableyRise() public view returns(uint256) { return yRiseToken.balanceOf(address(this)); } }
Starts the saleOnly the contract owner can call this function
function startSale() public { require(msg.sender == owner && startDate==0); startDate=now; }
354,846