file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../common/financial-product-libraries/long-short-pair-libraries/LongShortPairFinancialProductLibrary.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../common/interfaces/AddressWhitelistInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title Long Short Pair. * @notice Uses a combination of long and short tokens to tokenize the bounded price exposure to a given identifier. */ contract LongShortPair is Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /********************************************* * LONG SHORT PAIR DATA STRUCTURES * *********************************************/ // Define the contract's constructor parameters as a struct to enable more variables to be specified. struct ConstructorParams { string pairName; // Name of the long short pair contract. uint64 expirationTimestamp; // Unix timestamp of when the contract will expire. uint256 collateralPerPair; // How many units of collateral are required to mint one pair of synthetic tokens. bytes32 priceIdentifier; // Price identifier, registered in the DVM for the long short pair. ExpandedIERC20 longToken; // Token used as long in the LSP. Mint and burn rights needed by this contract. ExpandedIERC20 shortToken; // Token used as short in the LSP. Mint and burn rights needed by this contract. IERC20 collateralToken; // Collateral token used to back LSP synthetics. LongShortPairFinancialProductLibrary financialProductLibrary; // Contract providing settlement payout logic. bytes customAncillaryData; // Custom ancillary data to be passed along with the price request to the OO. uint256 prepaidProposerReward; // Preloaded reward to incentivize settlement price proposals. uint256 optimisticOracleLivenessTime; // OO liveness time for price requests. uint256 optimisticOracleProposerBond; // OO proposer bond for price requests. FinderInterface finder; // DVM finder to find other UMA ecosystem contracts. address timerAddress; // Timer used to synchronize contract time in testing. Set to 0x000... in production. } enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } // @dev note contractState and expirationTimestamp are declared in this order so they use the same storage slot. ContractState public contractState; uint64 public expirationTimestamp; string public pairName; // Amount of collateral a pair of tokens is always redeemable for. uint256 public collateralPerPair; // Price returned from the Optimistic oracle at settlement time. int256 public expiryPrice; // Number between 0 and 1e18 to allocate collateral between long & short tokens at redemption. 0 entitles each short // to collateralPerPair and long worth 0. 1e18 makes each long worth collateralPerPair and short 0. uint256 public expiryPercentLong; bytes32 public priceIdentifier; IERC20 public collateralToken; ExpandedIERC20 public longToken; ExpandedIERC20 public shortToken; FinderInterface public finder; LongShortPairFinancialProductLibrary public financialProductLibrary; // Optimistic oracle customization parameters. bytes public customAncillaryData; uint256 public prepaidProposerReward; uint256 public optimisticOracleLivenessTime; uint256 public optimisticOracleProposerBond; /**************************************** * EVENTS * ****************************************/ event TokensCreated(address indexed sponsor, uint256 indexed collateralUsed, uint256 indexed tokensMinted); event TokensRedeemed(address indexed sponsor, uint256 indexed collateralReturned, uint256 indexed tokensRedeemed); event ContractExpired(address indexed caller); event PositionSettled(address indexed sponsor, uint256 collateralReturned, uint256 longTokens, uint256 shortTokens); /**************************************** * MODIFIERS * ****************************************/ modifier preExpiration() { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); _; } modifier postExpiration() { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); _; } modifier onlyOpenState() { require(contractState == ContractState.Open, "Contract state is not Open"); _; } /** * @notice Construct the LongShortPair * @param params Constructor params used to initialize the LSP. Key-valued object with the following structure: * pairName: Name of the long short pair contract. * expirationTimestamp: Unix timestamp of when the contract will expire. * collateralPerPair: How many units of collateral are required to mint one pair of synthetic tokens. * priceIdentifier: Price identifier, registered in the DVM for the long short pair. * longToken: Token used as long in the LSP. Mint and burn rights needed by this contract. * shortToken: Token used as short in the LSP. Mint and burn rights needed by this contract. * collateralToken: Collateral token used to back LSP synthetics. * financialProductLibrary: Contract providing settlement payout logic. * customAncillaryData: Custom ancillary data to be passed along with the price request to the OO. * prepaidProposerReward: Preloaded reward to incentivize settlement price proposals. * optimisticOracleLivenessTime: OO liveness time for price requests. * optimisticOracleProposerBond: OO proposer bond for price requests. * finder: DVM finder to find other UMA ecosystem contracts. * timerAddress: Timer used to synchronize contract time in testing. Set to 0x000... in production. */ constructor(ConstructorParams memory params) Testable(params.timerAddress) { finder = params.finder; require(bytes(params.pairName).length > 0, "Pair name cant be empty"); require(params.expirationTimestamp > getCurrentTime(), "Expiration timestamp in past"); require(params.collateralPerPair > 0, "Collateral per pair cannot be 0"); require(_getIdentifierWhitelist().isIdentifierSupported(params.priceIdentifier), "Identifier not registered"); require(address(_getOptimisticOracle()) != address(0), "Invalid finder"); require(address(params.financialProductLibrary) != address(0), "Invalid FinancialProductLibrary"); require(_getCollateralWhitelist().isOnWhitelist(address(params.collateralToken)), "Collateral not whitelisted"); require(params.optimisticOracleLivenessTime > 0, "OO liveness cannot be 0"); require(params.optimisticOracleLivenessTime < 5200 weeks, "OO liveness too large"); pairName = params.pairName; expirationTimestamp = params.expirationTimestamp; collateralPerPair = params.collateralPerPair; priceIdentifier = params.priceIdentifier; longToken = params.longToken; shortToken = params.shortToken; collateralToken = params.collateralToken; financialProductLibrary = params.financialProductLibrary; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.stampAncillaryData(params.customAncillaryData, address(this)).length <= optimisticOracle.ancillaryBytesLimit(), "Ancillary Data too long" ); customAncillaryData = params.customAncillaryData; prepaidProposerReward = params.prepaidProposerReward; optimisticOracleLivenessTime = params.optimisticOracleLivenessTime; optimisticOracleProposerBond = params.optimisticOracleProposerBond; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Creates a pair of long and short tokens equal in number to tokensToCreate. Pulls the required collateral * amount into this contract, defined by the collateralPerPair value. * @dev The caller must approve this contract to transfer `tokensToCreate * collateralPerPair` amount of collateral. * @param tokensToCreate number of long and short synthetic tokens to create. * @return collateralUsed total collateral used to mint the synthetics. */ function create(uint256 tokensToCreate) public preExpiration() nonReentrant() returns (uint256 collateralUsed) { // Note the use of mulCeil to prevent small collateralPerPair causing rounding of collateralUsed to 0 enabling // callers to mint dust LSP tokens without paying any collateral. collateralUsed = FixedPoint.Unsigned(tokensToCreate).mulCeil(FixedPoint.Unsigned(collateralPerPair)).rawValue; collateralToken.safeTransferFrom(msg.sender, address(this), collateralUsed); require(longToken.mint(msg.sender, tokensToCreate)); require(shortToken.mint(msg.sender, tokensToCreate)); emit TokensCreated(msg.sender, collateralUsed, tokensToCreate); } /** * @notice Redeems a pair of long and short tokens equal in number to tokensToRedeem. Returns the commensurate * amount of collateral to the caller for the pair of tokens, defined by the collateralPerPair value. * @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`. * @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long * and short tokens are burned, rather than transferred, from the caller. * @param tokensToRedeem number of long and short synthetic tokens to redeem. * @return collateralReturned total collateral returned in exchange for the pair of synthetics. */ function redeem(uint256 tokensToRedeem) public nonReentrant() returns (uint256 collateralReturned) { require(longToken.burnFrom(msg.sender, tokensToRedeem)); require(shortToken.burnFrom(msg.sender, tokensToRedeem)); collateralReturned = FixedPoint.Unsigned(tokensToRedeem).mul(FixedPoint.Unsigned(collateralPerPair)).rawValue; collateralToken.safeTransfer(msg.sender, collateralReturned); emit TokensRedeemed(msg.sender, collateralReturned, tokensToRedeem); } /** * @notice Settle long and/or short tokens in for collateral at a rate informed by the contract settlement. * @dev Uses financialProductLibrary to compute the redemption rate between long and short tokens. * @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`. * @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long * and short tokens are burned, rather than transferred, from the caller. * @param longTokensToRedeem number of long tokens to settle. * @param shortTokensToRedeem number of short tokens to settle. * @return collateralReturned total collateral returned in exchange for the pair of synthetics. */ function settle(uint256 longTokensToRedeem, uint256 shortTokensToRedeem) public postExpiration() nonReentrant() returns (uint256 collateralReturned) { // If the contract state is open and postExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired contract"); // Get the current settlement price and store it. If it is not resolved, will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); // Cap the return value at 1. expiryPercentLong = Math.min( financialProductLibrary.percentageLongCollateralAtExpiry(expiryPrice), FixedPoint.fromUnscaledUint(1).rawValue ); contractState = ContractState.ExpiredPriceReceived; } require(longToken.burnFrom(msg.sender, longTokensToRedeem)); require(shortToken.burnFrom(msg.sender, shortTokensToRedeem)); // expiryPercentLong is a number between 0 and 1e18. 0 means all collateral goes to short tokens and 1e18 means // all collateral goes to the long token. Total collateral returned is the sum of payouts. uint256 longCollateralRedeemed = FixedPoint .Unsigned(longTokensToRedeem) .mul(FixedPoint.Unsigned(collateralPerPair)) .mul(FixedPoint.Unsigned(expiryPercentLong)) .rawValue; uint256 shortCollateralRedeemed = FixedPoint .Unsigned(shortTokensToRedeem) .mul(FixedPoint.Unsigned(collateralPerPair)) .mul(FixedPoint.fromUnscaledUint(1).sub(FixedPoint.Unsigned(expiryPercentLong))) .rawValue; collateralReturned = longCollateralRedeemed + shortCollateralRedeemed; collateralToken.safeTransfer(msg.sender, collateralReturned); emit PositionSettled(msg.sender, collateralReturned, longTokensToRedeem, shortTokensToRedeem); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ function expire() public postExpiration() onlyOpenState() nonReentrant() { _requestOraclePriceExpiration(); contractState = ContractState.ExpiredPriceRequested; emit ContractExpired(msg.sender); } /**************************************** * GLOBAL ACCESSORS FUNCTIONS * ****************************************/ /** * @notice Returns the number of long and short tokens a sponsor wallet holds. * @param sponsor address of the sponsor to query. * @return [uint256, uint256]. First is long tokens held by sponsor and second is short tokens held by sponsor. */ function getPositionTokens(address sponsor) public view nonReentrantView() returns (uint256, uint256) { return (longToken.balanceOf(sponsor), shortToken.balanceOf(sponsor)); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _getOraclePriceExpiration(uint256 requestedTime) internal returns (int256) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require(optimisticOracle.hasPrice(address(this), priceIdentifier, requestedTime, customAncillaryData)); int256 oraclePrice = optimisticOracle.settleAndGetPrice(priceIdentifier, requestedTime, customAncillaryData); return oraclePrice; } function _requestOraclePriceExpiration() internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Use the prepaidProposerReward as the proposer reward. if (prepaidProposerReward > 0) collateralToken.safeApprove(address(optimisticOracle), prepaidProposerReward); optimisticOracle.requestPrice( priceIdentifier, expirationTimestamp, customAncillaryData, collateralToken, prepaidProposerReward ); // Set the Optimistic oracle liveness for the price request. optimisticOracle.setCustomLiveness( priceIdentifier, expirationTimestamp, customAncillaryData, optimisticOracleLivenessTime ); // Set the Optimistic oracle proposer bond for the price request. optimisticOracle.setBond( priceIdentifier, expirationTimestamp, customAncillaryData, optimisticOracleProposerBond ); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getCollateralWhitelist() internal view returns (AddressWhitelistInterface) { return AddressWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../../../common/implementation/FixedPoint.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } abstract contract LongShortPairFinancialProductLibrary { function percentageLongCollateralAtExpiry(int256 expiryPrice) public view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run in production, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return block.timestamp; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() { // Storing an initial non-zero value makes deployment a bit more expensive, but in exchange the refund on every // call to nonReentrant will be lower in amount. Since refunds are capped to a 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. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` function is not supported. It is possible to * prevent this from happening by making the `nonReentrant` function external, and making it call a `private` * function that does the actual state modification. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being // re-entered. Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and // then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @dev Burns `value` tokens owned by `recipient`. * @param recipient address to burn tokens from. * @param value amount of tokens to burn. */ function burnFrom(address recipient, uint256 value) external virtual returns (bool); /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; interface AddressWhitelistInterface { function addToWhitelist(address newElement) external; function removeFromWhitelist(address newElement) external virtual; function isOnWhitelist(address newElement) external view virtual returns (bool); function getWhitelist() external view virtual returns (address[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length over a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); /** * @notice Returns the state of a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State enum value. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return true if price has resolved or settled, false otherwise. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); function stampAncillaryData(bytes memory ancillaryData, address requester) public view virtual returns (bytes memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; bytes32 public constant Bridge = "Bridge"; bytes32 public constant GenericHandler = "GenericHandler"; } // 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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SignedSafeMath { /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { return a / b; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { return a - b; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { return a + b; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() { currentTime = block.timestamp; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the currentTime variable set in the Timer. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } }
Price returned from the Optimistic oracle at settlement time.
int256 public expiryPrice;
148,146
[ 1, 5147, 2106, 628, 326, 19615, 5846, 20865, 622, 26319, 806, 813, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 509, 5034, 1071, 10839, 5147, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.7.0; import "hardhat/console.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { Ownable , SimpleProxy, ReentrancyGuard } from "./SimpleProxy.sol"; contract PresalePoolerFactory is ERC20, Ownable, ReentrancyGuard { IERC20 public token; address public targetAddr; uint256 public limit; uint256 public maxLimit; uint256 public minSend; uint256 public claimPerETH; uint FEE = 500;//5% uint BASE = 10000; bool public bought = false; bool public claimedTokens = false; bool public forceRetrive; mapping(address => uint) deposits; SimpleProxy[] deployedProxies; address[] depositors; constructor(address _token, address _presaleAddr, uint256 investLimitPerAddr, uint256 maxL, uint256 _minSend ) ERC20 (string(abi.encodePacked("PrePool ", ERC20(_token).name())), string(abi.encodePacked("p", ERC20(_token).symbol()))) { token = IERC20(_token); targetAddr = _presaleAddr; limit = investLimitPerAddr; maxLimit = maxL;//Max hardcap of sale minSend = _minSend; } function getFee(uint value) internal view returns (uint) { return (value * FEE) / BASE; } function getDepositors() external view returns (address[] memory) { return depositors; } receive() external payable nonReentrant { if(msg.sender != targetAddr) { uint msgval = msg.value; uint256 fee = getFee(msgval); uint256 amountAfterFee = msgval - fee; //Take into account of current supply minus the fee address uint256 newAlloc = (totalSupply() - balanceOf(owner())) + amountAfterFee; uint256 refundAmount = newAlloc > maxLimit ? newAlloc - maxLimit : 0; uint256 mintAmount = amountAfterFee - refundAmount; if(refundAmount > 0) { //Refund back the difference (bool success,) = msg.sender.call{value: refundAmount }(""); require(success,"!refund"); } //Mint iou tokens to sender _mint(msg.sender,mintAmount); //Mint iou tokens to gov for fees _mint(owner(),fee); if(deposits[msg.sender] == 0) depositors.push(msg.sender);//Add depositor to array deposits[msg.sender] = (deposits[msg.sender] + msgval) - refundAmount; } else{ //Send any eth gotten via refund to owner() payable(owner()).transfer(msg.value); } } function deployProxies() internal { uint256 bal = address(this).balance; uint256 targetProxies = limit != 0 ? bal / limit : 1;//Only deploy 1 proxy if limit is 0 which means no limit per address deployedProxies = new SimpleProxy[](targetProxies); //Deploy multiple dsproxies to invest for(uint i=0;i<targetProxies;i++) { deployedProxies[i] = new SimpleProxy(); } } function getAvailableBal() internal view returns (uint) { uint bal = address(this).balance; uint balgov = balanceOf(owner()); if(bal > balgov) return bal - balgov; else if (bal < minSend) return 0;//Dont send if we dont match minsend of sale contract else if (bal <= balgov) return 0; return 0; } function buy() external onlyOwner { require(!bought,"Already bought"); deployProxies(); uint targval = limit; uint256 balE = getAvailableBal(); for(uint i=0;i<deployedProxies.length && balE != 0 ;i++) { //Send limit to wallet and execute to buy tokens deployedProxies[i].executeWithValue{value: targval}(targetAddr,new bytes(0)); balE = getAvailableBal();//Update balance if(balE <= limit) {targval = balE;} //Call approve on target so that we can pull the target tokens deployedProxies[i].execute(address(token),abi.encodeWithSignature("approve(address,uint256)", address(this),uint256(-1))); } bought = true; } //Call this if you want to opt out of the pool after depositing function getETH() external nonReentrant { require(!bought,"funds not available to claim"); uint balCaller = balanceOf(msg.sender); require(balCaller > 0,"No Poolshare tokens"); uint depAmount = deposits[msg.sender]; require(depAmount > 0,"No deposited eth"); _burn(msg.sender, balCaller); deposits[msg.sender] = 0;//Reset deposits amount (bool success,) = msg.sender.call{value : depAmount}(""); require(success,"!getGovFees"); } //This sends owner() fees,will only send if tokens were bought successfully function getGovFees() external { require(bought,"Buy didnt complete"); uint govbal = balanceOf(owner()); _burn(owner(), govbal); (bool success,bytes memory returnData) = owner().call{value : govbal}(""); require(success,string(returnData)); } function pullTokens() external { require(!claimedTokens,"Already claimed"); //Call transferfrom from all proxies to this addr for(uint i=0;i<deployedProxies.length;i++) { token.transferFrom(address(deployedProxies[i]), address(this), token.balanceOf(address(deployedProxies[i]))); } require(token.balanceOf(address(this)) > 0,"No tokens gotten"); claimPerETH = token.balanceOf(address(this)) / totalSupply(); claimedTokens = true; } function claimTokens() external { require(claimedTokens,"Not claimed yet"); uint256 claimable = balanceOf(msg.sender) * claimPerETH; require(claimable > 0,"No tokens claimable"); _burn(msg.sender,balanceOf(msg.sender)); token.transfer(msg.sender,claimable); } function enableForceRetrive() external onlyOwner { forceRetrive = true; } function retriveBnb() external onlyOwner { //Use this to retrive bnb if buy didnt happen or there is excess require(bought || totalSupply() == 0 || forceRetrive,"Failed prerequisites"); (bool success,bytes memory returnData) = owner().call{value : address(this).balance}(""); require(success,string(returnData)); } function retriveTokens() external onlyOwner { require(bought || totalSupply() == 0 || forceRetrive,"Failed prerequisites"); token.transfer(owner(),token.balanceOf(address(this))); } //Used to destruct proxies that are not needed function destructProxies() external onlyOwner { for(uint i=0;i<deployedProxies.length;i++) { deployedProxies[i].destruct(); } } function retriveTokensFromProxies(address _token) external onlyOwner { IERC20 itoken = IERC20(_token); for(uint i=0;i<deployedProxies.length;i++) { //Transfer to this address deployedProxies[i].execute(_token,abi.encodeWithSignature("transfer(address,uint256)", address(this),itoken.balanceOf(address(deployedProxies[i])))); } } function recoverToken(address _token) external onlyOwner { IERC20 itoken = IERC20(_token); itoken.transfer(owner(),itoken.balanceOf(address(this))); } //Used by owner to claim tokens if we have to call to proxies manually at some point function executeCall(address target,bytes calldata data) external onlyOwner { (bool success,) = target.call{value:0}(data); require(success,"External call failed"); } function executeCallOnProxy(address target,bytes calldata data,uint index) external onlyOwner { deployedProxies[index].execute(target,data); } function executeCallOnProxies(address target,bytes calldata data) external onlyOwner { for(uint i=0;i<deployedProxies.length;i++) { deployedProxies[i].execute(target,data); } } }
Mint iou tokens to gov for fees
_mint(owner(),fee);
1,848,163
[ 1, 49, 474, 277, 1395, 2430, 358, 31841, 364, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 389, 81, 474, 12, 8443, 9334, 21386, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.7; import "../strategy-joe-rush-farm-base.sol"; contract StrategyJoeAvaxFrax is StrategyJoeRushFarmBase { uint256 public avax_frax_poolId = 33; address public joe_avax_frax_lp = 0x862905a82382Db9405a40DCAa8Ee9e8F4af52C89; address public frax = 0xD24C2Ad096400B6FBcd2ad8B24E7acBc21A1da64; address public fxs = 0x214DB107654fF987AD859F34125307783fC8e387; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyJoeRushFarmBase( avax_frax_poolId, joe_avax_frax_lp, _governance, _strategist, _controller, _timelock ) {} function _takeFeeFraxToSnob(uint256 _keep) internal { address[] memory path = new address[](3); path[0] = frax; path[1] = wavax; path[2] = snob; IERC20(frax).safeApprove(joeRouter, 0); IERC20(frax).safeApprove(joeRouter, _keep); _swapTraderJoeWithPath(path, _keep); uint256 _snob = IERC20(snob).balanceOf(address(this)); uint256 _share = _snob.mul(revenueShare).div(revenueShareMax); IERC20(snob).safeTransfer( feeDistributor, _share ); IERC20(snob).safeTransfer( IController(controller).treasury(), _snob.sub(_share) ); } function _takeFeeFxsToSnob(uint256 _keep) internal { address[] memory path = new address[](3); path[0] = fxs; path[1] = wavax; path[2] = snob; IERC20(fxs).safeApprove(joeRouter, 0); IERC20(fxs).safeApprove(joeRouter, _keep); _swapTraderJoeWithPath(path, _keep); uint256 _snob = IERC20(snob).balanceOf(address(this)); uint256 _share = _snob.mul(revenueShare).div(revenueShareMax); IERC20(snob).safeTransfer( feeDistributor, _share ); IERC20(snob).safeTransfer( IController(controller).treasury(), _snob.sub(_share) ); } // **** State Mutations **** function harvest() public override onlyBenevolent { // Collects Joe tokens IMasterChefJoeV2(masterChefJoeV3).deposit(poolId, 0); // Take Avax Rewards uint256 _avax = address(this).balance; // get balance of native AVAX if (_avax > 0) { // wrap AVAX into ERC20 WAVAX(wavax).deposit{value: _avax}(); } uint256 _frax = IERC20(frax).balanceOf(address(this)); // get balance of FRAX Tokens uint256 _wavax = IERC20(wavax).balanceOf(address(this)); //get balance of WAVAX Tokens // In the case of WAVAX Rewards, swap WAVAX for FRAX if (_wavax > 0) { uint256 _keep1 = _wavax.mul(keep).div(keepMax); if (_keep1 > 0){ _takeFeeWavaxToSnob(_keep1); } _wavax = IERC20(wavax).balanceOf(address(this)); IERC20(wavax).safeApprove(joeRouter, 0); IERC20(wavax).safeApprove(joeRouter, _wavax.div(2)); _swapTraderJoe(wavax, frax, _wavax.div(2)); } // In the case of FRAX Rewards, swap FRAX for WAVAX if (_frax > 0) { uint256 _keep2 = _frax.mul(keep).div(keepMax); if (_keep2 > 0){ _takeFeeFraxToSnob(_keep2); } _frax = IERC20(frax).balanceOf(address(this)); IERC20(frax).safeApprove(joeRouter, 0); IERC20(frax).safeApprove(joeRouter, _frax.div(2)); _swapTraderJoe(frax, wavax, _frax.div(2)); } uint256 _joe = IERC20(joe).balanceOf(address(this)); if (_joe > 0) { // 10% is sent to treasury uint256 _keep = _joe.mul(keep).div(keepMax); if (_keep > 0) { _takeFeeJoeToSnob(_keep); } _joe = IERC20(joe).balanceOf(address(this)); IERC20(joe).safeApprove(joeRouter, 0); IERC20(joe).safeApprove(joeRouter, _joe); _swapTraderJoe(joe, wavax, _joe.div(2)); _swapTraderJoe(joe, frax, _joe.div(2)); } uint256 _fxs = IERC20(fxs).balanceOf(address(this)); if (_fxs > 0) { // 10% is sent to treasury uint256 _keep = _fxs.mul(keep).div(keepMax); if (_keep > 0) { _takeFeeFxsToSnob(_keep); } _fxs = IERC20(fxs).balanceOf(address(this)); IERC20(fxs).safeApprove(joeRouter, 0); IERC20(fxs).safeApprove(joeRouter, _fxs); _swapTraderJoe(fxs, wavax, _fxs.div(2)); _swapTraderJoe(fxs, frax, _fxs.div(2)); } // Adds in liquidity for AVAX/FRAX _frax = IERC20(frax).balanceOf(address(this)); _wavax = IERC20(wavax).balanceOf(address(this)); if (_frax > 0 && _wavax > 0) { IERC20(frax).safeApprove(joeRouter, 0); IERC20(frax).safeApprove(joeRouter, _frax); IERC20(wavax).safeApprove(joeRouter, 0); IERC20(wavax).safeApprove(joeRouter, _wavax); IJoeRouter(joeRouter).addLiquidity( frax, wavax, _frax, _wavax, 0, 0, address(this), now + 60 ); // Donates DUST _frax = IERC20(frax).balanceOf(address(this)); _wavax = IERC20(wavax).balanceOf(address(this)); _joe = IERC20(joe).balanceOf(address(this)); _fxs = IERC20(fxs).balanceOf(address(this)); if (_frax > 0){ IERC20(frax).transfer( IController(controller).treasury(), _frax ); } if (_wavax > 0){ IERC20(wavax).safeTransfer( IController(controller).treasury(), _wavax ); } if (_joe > 0){ IERC20(joe).transfer( IController(controller).treasury(), _joe ); } if (_fxs > 0){ IERC20(fxs).transfer( IController(controller).treasury(), _fxs ); } } _distributePerformanceFeesAndDeposit(); } // **** Views **** function getName() external override pure returns (string memory) { return "StrategyJoeAvaxFrax"; } }
Collects Joe tokens Take Avax Rewards
function harvest() public override onlyBenevolent { IMasterChefJoeV2(masterChefJoeV3).deposit(poolId, 0); }
919,106
[ 1, 28791, 804, 15548, 2430, 17129, 8789, 651, 534, 359, 14727, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17895, 26923, 1435, 1071, 3849, 1338, 38, 4009, 15416, 319, 288, 203, 3639, 6246, 2440, 39, 580, 74, 46, 15548, 58, 22, 12, 7525, 39, 580, 74, 46, 15548, 58, 23, 2934, 323, 1724, 12, 6011, 548, 16, 374, 1769, 203, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title 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]; } } /** * @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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /* * CCR Token Smart Contract. @ 2018 by Kapsus Technoloies Limited (www.kapsustech.com). * Author: Susanta Saren <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93f1e6e0fafdf6e0e0d3f0e1eae3e7fcf0f2e0fbf1f2f0f8e1f6f1f2e7f6bdf0fcfe">[email&#160;protected]</a>> */ contract CCRToken is MintableToken, PausableToken { using SafeMath for uint256; string public constant name = "CryptoCashbackRebate Token"; string public constant symbol = "CCR"; uint32 public constant decimals = 18; } /* * CCR Token Crowdsale Smart Contract. @ 2018 by Kapsus Technoloies Limited (www.kapsustech.com). * Author: Susanta Saren <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4a6b1b7adaaa1b7b784a7b6bdb4b0aba7a5b7aca6a5a7afb6a1a6a5b0a1eaa7aba9">[email&#160;protected]</a>> */ contract CCRCrowdsale is Ownable { using SafeMath for uint; event TokensPurchased(address indexed buyer, uint256 ether_amount); event CCRCrowdsaleClosed(); CCRToken public token = new CCRToken(); address public multisigVault = 0x4f39C2f050b07b3c11B08f2Ec452eD603a69839D; uint256 public totalReceived = 0; uint256 public hardcap = 416667 ether; uint256 public minimum = 0.10 ether; uint256 public altDeposits = 0; uint256 public start = 1521338401; // 18 March, 2018 02:00:01 GMT bool public saleOngoing = true; /** * @dev modifier to allow token creation only when the sale IS ON */ modifier isSaleOn() { require(start <= now && saleOngoing); _; } /** * @dev modifier to prevent buying tokens below the minimum required */ modifier isAtLeastMinimum() { require(msg.value >= minimum); _; } /** * @dev modifier to allow token creation only when the hardcap has not been reached */ modifier isUnderHardcap() { require(totalReceived + altDeposits <= hardcap); _; } function CCRCrowdsale() public { token.pause(); } /* * @dev Receive eth from the sender * @param sender the sender to receive tokens. */ function acceptPayment(address sender) public isAtLeastMinimum isUnderHardcap isSaleOn payable { totalReceived = totalReceived.add(msg.value); multisigVault.transfer(this.balance); TokensPurchased(sender, msg.value); } /** * @dev Allows the owner to set the starting time. * @param _start the new _start */ function setStart(uint256 _start) external onlyOwner { start = _start; } /** * @dev Allows the owner to set the minimum purchase. * @param _minimum the new _minimum */ function setMinimum(uint256 _minimum) external onlyOwner { minimum = _minimum; } /** * @dev Allows the owner to set the hardcap. * @param _hardcap the new hardcap */ function setHardcap(uint256 _hardcap) external onlyOwner { hardcap = _hardcap; } /** * @dev Allows to set the total alt deposit measured in ETH to make sure the hardcap includes other deposits * @param totalAltDeposits total amount ETH equivalent */ function setAltDeposits(uint256 totalAltDeposits) external onlyOwner { altDeposits = totalAltDeposits; } /** * @dev Allows the owner to set the multisig contract. * @param _multisigVault the multisig contract address */ function setMultisigVault(address _multisigVault) external onlyOwner { require(_multisigVault != address(0)); multisigVault = _multisigVault; } /** * @dev Allows the owner to stop the sale * @param _saleOngoing whether the sale is ongoing or not */ function setSaleOngoing(bool _saleOngoing) external onlyOwner { saleOngoing = _saleOngoing; } /** * @dev Allows the owner to close the sale and stop accepting ETH. * The ownership of the token contract is transfered to this owner. */ function closeSale() external onlyOwner { token.transferOwnership(owner); CCRCrowdsaleClosed(); } /** * @dev Allows the owner to transfer ERC20 tokens to the multisig vault * @param _token the contract address of the ERC20 contract */ function retrieveTokens(address _token) external onlyOwner { ERC20 foreignToken = ERC20(_token); foreignToken.transfer(multisigVault, foreignToken.balanceOf(this)); } /** * @dev Fallback function which receives ether */ function() external payable { acceptPayment(msg.sender); } }
* @dev modifier to prevent buying tokens below the minimum required/
modifier isAtLeastMinimum() { require(msg.value >= minimum); _; }
10,740,896
[ 1, 20597, 358, 5309, 30143, 310, 2430, 5712, 326, 5224, 1931, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 353, 25070, 13042, 1435, 288, 203, 565, 2583, 12, 3576, 18, 1132, 1545, 5224, 1769, 203, 565, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./GovernorBravoInterfaces.sol"; contract GovernorBravoDelegate is GovernorBravoDelegateStorageV2, GovernorBravoEvents { /// @notice The name of this contract string public constant name = "Mind Uploading DAO Governor"; /// @notice The minimum setable proposal threshold uint public constant MIN_PROPOSAL_THRESHOLD = 5000000e18; // 5,000,000 Comp /// @notice The maximum setable proposal threshold uint public constant MAX_PROPOSAL_THRESHOLD = 10000000e18; //10,000,000 Comp /// @notice The minimum setable voting period uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours /// @notice The max setable voting period uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks /// @notice The min setable voting delay uint public constant MIN_VOTING_DELAY = 1; /// @notice The max setable voting delay uint public constant MAX_VOTING_DELAY = 40320; // About 1 week /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed uint public constant quorumVotes = 40000000e18; // 40,000,000 = 4% of Comp /// @notice The maximum number of actions that can be included in a proposal uint public constant proposalMaxOperations = 10; // 10 actions /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); /** * @notice Used to initialize the contract during delegator contructor * @param timelock_ The address of the Timelock * @param comp_ The address of the COMP token * @param votingPeriod_ The initial voting period * @param votingDelay_ The initial voting delay * @param proposalThreshold_ The initial proposal threshold */ function initialize(address timelock_, address comp_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once"); require(msg.sender == admin, "GovernorBravo::initialize: admin only"); require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address"); require(comp_ != address(0), "GovernorBravo::initialize: invalid comp address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); comp = CompInterface(comp_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; } /** * @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold * @param targets Target addresses for proposal calls * @param values Eth values for proposal calls * @param signatures Function signatures for proposal calls * @param calldatas Calldatas for proposal calls * @param description String description of the proposal * @return Proposal id of new proposal */ function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { // Reject proposals before initiating as Governor require(initialProposalId != 0, "GovernorBravo::propose: Governor Bravo not active"); // Allow addresses above proposal threshold and whitelisted addresses to propose require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold || isWhitelisted(msg.sender), "GovernorBravo::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorBravo::propose: must provide actions"); require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal"); } uint startBlock = add256(block.number, votingDelay); uint endBlock = add256(startBlock, votingPeriod); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, abstainVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } /** * @notice Queues a proposal of state succeeded * @param proposalId The id of the proposal to queue */ function queue(uint proposalId) external { require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } /** * @notice Executes a queued proposal if eta has passed * @param proposalId The id of the proposal to execute */ function execute(uint proposalId) external payable { require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } /** * @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold * @param proposalId The id of the proposal to cancel */ function cancel(uint proposalId) external { require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; // Proposer can cancel if(msg.sender != proposal.proposer) { // Whitelisted proposers can't be canceled for falling below proposal threshold if(isWhitelisted(proposal.proposer)) { require((comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold) && msg.sender == whitelistGuardian, "GovernorBravo::cancel: whitelisted proposer"); } else { require((comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold), "GovernorBravo::cancel: proposer above threshold"); } } proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } /** * @notice Gets actions of a proposal * @param proposalId the id of the proposal * @return Targets, values, signatures, and calldatas of the proposal actions */ function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice Gets the receipt for a voter on a given proposal * @param proposalId the id of proposal * @param voter The address of the voter * @return The voting receipt */ function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } /** * @notice Gets the state of a proposal * @param proposalId The id of the proposal * @return Proposal state */ function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } /** * @notice Cast a vote for a proposal * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain */ function castVote(uint proposalId, uint8 support) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), ""); } /** * @notice Cast a vote for a proposal with a reason * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @param reason The reason given for the vote by the voter */ function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason); } /** * @notice Cast a vote for a proposal by signature * @dev External function that accepts EIP-712 signatures for voting on proposals. */ function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature"); emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), ""); } /** * @notice Internal function that caries out voting logic * @param voter The voter that is casting their vote * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @return The number of votes cast */ function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) { require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed"); require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted"); uint96 votes = comp.getPriorVotes(voter, proposal.startBlock); if (support == 0) { proposal.againstVotes = add256(proposal.againstVotes, votes); } else if (support == 1) { proposal.forVotes = add256(proposal.forVotes, votes); } else if (support == 2) { proposal.abstainVotes = add256(proposal.abstainVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; return votes; } /** * @notice View function which returns if an account is whitelisted * @param account Account to check white list status of * @return If the account is whitelisted */ function isWhitelisted(address account) public view returns (bool) { return (whitelistAccountExpirations[account] > now); } /** * @notice Admin function for setting the voting delay * @param newVotingDelay new voting delay, in blocks */ function _setVotingDelay(uint newVotingDelay) external { require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only"); require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::_setVotingDelay: invalid voting delay"); uint oldVotingDelay = votingDelay; votingDelay = newVotingDelay; emit VotingDelaySet(oldVotingDelay,votingDelay); } /** * @notice Admin function for setting the voting period * @param newVotingPeriod new voting period, in blocks */ function _setVotingPeriod(uint newVotingPeriod) external { require(msg.sender == admin, "GovernorBravo::_setVotingPeriod: admin only"); require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::_setVotingPeriod: invalid voting period"); uint oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); } /** * @notice Admin function for setting the proposal threshold * @dev newProposalThreshold must be greater than the hardcoded min * @param newProposalThreshold new proposal threshold */ function _setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorBravo::_setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::_setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); } /** * @notice Admin function for setting the whitelist expiration as a timestamp for an account. Whitelist status allows accounts to propose without meeting threshold * @param account Account address to set whitelist expiration for * @param expiration Expiration for account whitelist status as timestamp (if now < expiration, whitelisted) */ function _setWhitelistAccountExpiration(address account, uint expiration) external { require(msg.sender == admin || msg.sender == whitelistGuardian, "GovernorBravo::_setWhitelistAccountExpiration: admin only"); whitelistAccountExpirations[account] = expiration; emit WhitelistAccountExpirationSet(account, expiration); } /** * @notice Admin function for setting the whitelistGuardian. WhitelistGuardian can cancel proposals from whitelisted addresses * @param account Account to set whitelistGuardian to (0x0 to remove whitelistGuardian) */ function _setWhitelistGuardian(address account) external { require(msg.sender == admin, "GovernorBravo::_setWhitelistGuardian: admin only"); address oldGuardian = whitelistGuardian; whitelistGuardian = account; emit WhitelistGuardianSet(oldGuardian, whitelistGuardian); } /** * @notice Initiate the GovernorBravo contract * @dev Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count * @param governorAlpha The address for the Governor to continue the proposal id count from */ function _initiate(address governorAlpha) external { require(msg.sender == admin, "GovernorBravo::_initiate: admin only"); require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once"); proposalCount = GovernorAlpha(governorAlpha).proposalCount(); initialProposalId = proposalCount; timelock.acceptAdmin(); } /** * @notice Begins transfer of admin rights. 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. */ function _setPendingAdmin(address newPendingAdmin) external { // Check caller = admin require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() external { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:_acceptAdmin: pending admin only"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainIdInternal() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; contract GovernorBravoEvents { /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal /// @param voter The address which casted a vote /// @param proposalId The proposal id which was voted on /// @param support Support value for the vote. 0=against, 1=for, 2=abstain /// @param votes Number of votes which were cast by the voter /// @param reason The reason given for the vote by the voter event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); /// @notice An event emitted when the voting delay is set event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay); /// @notice An event emitted when the voting period is set event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod); /// @notice Emitted when implementation is changed event NewImplementation(address oldImplementation, address newImplementation); /// @notice Emitted when proposal threshold is set event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold); /// @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /// @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); /// @notice Emitted when whitelist account expiration is set event WhitelistAccountExpirationSet(address account, uint expiration); /// @notice Emitted when the whitelistGuardian is set event WhitelistGuardianSet(address oldGuardian, address newGuardian); } contract GovernorBravoDelegatorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of Governor address public implementation; } /** * @title Storage for Governor Bravo Delegate * @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new * contract which implements GovernorBravoDelegateStorageV1 and following the naming convention * GovernorBravoDelegateStorageVX. */ contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage { /// @notice The delay before voting on a proposal may take place, once proposed, in blocks uint public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint public votingPeriod; /// @notice The number of votes required in order for a voter to become a proposer uint public proposalThreshold; /// @notice Initial proposal id set at become uint public initialProposalId; /// @notice The total number of proposals uint public proposalCount; /// @notice The address of the Compound Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Compound governance token CompInterface public comp; /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Current number of votes for abstaining for this proposal uint abstainVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal or abstains uint8 support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } contract GovernorBravoDelegateStorageV2 is GovernorBravoDelegateStorageV1 { /// @notice Stores the expiration of account whitelist status as a timestamp mapping (address => uint) public whitelistAccountExpirations; /// @notice Address which manages whitelisted proposals and whitelist accounts address public whitelistGuardian; } interface TimelockInterface { function delay() external view returns (uint); function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface CompInterface { function getPriorVotes(address account, uint blockNumber) external view returns (uint96); } interface GovernorAlpha { /// @notice The total number of proposals function proposalCount() external returns (uint); }
* @notice Admin function for setting the whitelistGuardian. WhitelistGuardian can cancel proposals from whitelisted addresses @param account Account to set whitelistGuardian to (0x0 to remove whitelistGuardian)/
function _setWhitelistGuardian(address account) external { require(msg.sender == admin, "GovernorBravo::_setWhitelistGuardian: admin only"); address oldGuardian = whitelistGuardian; whitelistGuardian = account; emit WhitelistGuardianSet(oldGuardian, whitelistGuardian); }
6,980,057
[ 1, 4446, 445, 364, 3637, 326, 10734, 16709, 2779, 18, 3497, 7523, 16709, 2779, 848, 3755, 450, 22536, 628, 26944, 6138, 225, 2236, 6590, 358, 444, 10734, 16709, 2779, 358, 261, 20, 92, 20, 358, 1206, 10734, 16709, 2779, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 389, 542, 18927, 16709, 2779, 12, 2867, 2236, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3981, 16, 315, 43, 1643, 29561, 38, 354, 12307, 2866, 67, 542, 18927, 16709, 2779, 30, 3981, 1338, 8863, 203, 3639, 1758, 1592, 16709, 2779, 273, 10734, 16709, 2779, 31, 203, 3639, 10734, 16709, 2779, 273, 2236, 31, 203, 203, 3639, 3626, 3497, 7523, 16709, 2779, 694, 12, 1673, 16709, 2779, 16, 10734, 16709, 2779, 1769, 203, 377, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; import "./LoanContract.sol"; contract LoanFactory { address[] public loans; address[] public borrowers; //may not be needed mapping(address => address) public borrowerLoanIndex; event LoanCreated(address loanAddress, address borrowerAddress); function loanCount() public view returns(uint256 _loanCount) { return loans.length; } // Gets the loan contract address for the given borrower address function getLoanForBorrower (address _borrowerAddress) public view returns(address _loanAddress) { return (borrowerLoanIndex[_borrowerAddress]); } // Creates a new loan contract with the data specified and adds it to the centralized loan repo function create ( uint _loanAmountInEthers, uint _repaymentDurationInDays, string _name, string _use ) public returns(address _loanAddress) { address borrowerAddress = msg.sender; uint fundRaisingDurationInDays = 30; //default to 30 for now address newLoanContract = new LoanContract( borrowerAddress, _loanAmountInEthers, fundRaisingDurationInDays, _repaymentDurationInDays, _name, _use ); loans.push(newLoanContract); borrowers.push(borrowerAddress); borrowerLoanIndex[borrowerAddress] = newLoanContract; LoanCreated(newLoanContract, borrowerAddress); return newLoanContract; } }
Gets the loan contract address for the given borrower address
function getLoanForBorrower (address _borrowerAddress) public view returns(address _loanAddress) { return (borrowerLoanIndex[_borrowerAddress]); }
12,755,356
[ 1, 3002, 326, 28183, 6835, 1758, 364, 326, 864, 29759, 264, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 1504, 304, 1290, 38, 15318, 264, 261, 2867, 389, 70, 15318, 264, 1887, 13, 1071, 1476, 1135, 12, 2867, 389, 383, 304, 1887, 13, 288, 203, 3639, 327, 261, 70, 15318, 264, 1504, 304, 1016, 63, 67, 70, 15318, 264, 1887, 19226, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IMasterChef.sol"; import "./interfaces/IVault.sol"; import "./interfaces/ILockManager.sol"; import "./interfaces/IERC20Extended.sol"; import "./lib/SafeERC20.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title RewardsManager * @dev Controls rewards distribution for network */ contract RewardsManager is ReentrancyGuard { using SafeERC20 for IERC20Extended; /// @notice Current owner of this contract address public owner; /// @notice Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardTokenDebt; // Reward debt for reward token. See explanation below. uint256 sushiRewardDebt; // Reward debt for Sushi rewards. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardsPerShare` (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. } /// @notice Info of each pool. struct PoolInfo { IERC20Extended token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per block. uint256 lastRewardBlock; // Last block number where reward tokens were distributed. uint256 accRewardsPerShare; // Accumulated reward tokens per share, times 1e12. See below. uint32 vestingPercent; // Percentage of rewards that vest (measured in bips: 500,000 bips = 50% of rewards) uint16 vestingPeriod; // Vesting period in days for vesting rewards uint16 vestingCliff; // Vesting cliff in days for vesting rewards uint256 totalStaked; // Total amount of token staked via Rewards Manager bool vpForDeposit; // Do users get voting power for deposits of this token? bool vpForVesting; // Do users get voting power for vesting balances? } /// @notice Reward token IERC20Extended public rewardToken; /// @notice SUSHI token IERC20Extended public sushiToken; /// @notice Sushi Master Chef IMasterChef public masterChef; /// @notice Vault for vesting tokens IVault public vault; /// @notice LockManager contract ILockManager public lockManager; /// @notice Reward tokens rewarded per block. uint256 public rewardTokensPerBlock; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Mapping of Sushi tokens to MasterChef pids mapping (address => uint256) public sushiPools; /// @notice Info of each user that stakes tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @notice Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// @notice The block number when rewards start. uint256 public startBlock; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /// @notice Event emitted when a user deposits funds in the rewards manager event Deposit(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds + rewards from the rewards manager event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds from the rewards manager without claiming rewards event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when new pool is added to the rewards manager event PoolAdded(uint256 indexed pid, address indexed token, uint256 allocPoints, uint256 totalAllocPoints, uint256 rewardStartBlock, uint256 sushiPid, bool vpForDeposit, bool vpForVesting); /// @notice Event emitted when pool allocation points are updated event PoolUpdated(uint256 indexed pid, uint256 oldAllocPoints, uint256 newAllocPoints, uint256 newTotalAllocPoints); /// @notice Event emitted when the owner of the rewards manager contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when the amount of reward tokens per block is updated event ChangedRewardTokensPerBlock(uint256 indexed oldRewardTokensPerBlock, uint256 indexed newRewardTokensPerBlock); /// @notice Event emitted when the rewards start block is set event SetRewardsStartBlock(uint256 indexed startBlock); /// @notice Event emitted when contract address is changed event ChangedAddress(string indexed addressType, address indexed oldAddress, address indexed newAddress); /** * @notice Create a new Rewards Manager contract * @param _owner owner of contract * @param _lockManager address of LockManager contract * @param _vault address of Vault contract * @param _rewardToken address of token that is being offered as a reward * @param _sushiToken address of SUSHI token * @param _masterChef address of SushiSwap MasterChef contract * @param _startBlock block number when rewards will start * @param _rewardTokensPerBlock initial amount of reward tokens to be distributed per block */ constructor( address _owner, address _lockManager, address _vault, address _rewardToken, address _sushiToken, address _masterChef, uint256 _startBlock, uint256 _rewardTokensPerBlock ) { owner = _owner; emit ChangedOwner(address(0), _owner); lockManager = ILockManager(_lockManager); emit ChangedAddress("LOCK_MANAGER", address(0), _lockManager); vault = IVault(_vault); emit ChangedAddress("VAULT", address(0), _vault); rewardToken = IERC20Extended(_rewardToken); emit ChangedAddress("REWARD_TOKEN", address(0), _rewardToken); sushiToken = IERC20Extended(_sushiToken); emit ChangedAddress("SUSHI_TOKEN", address(0), _sushiToken); masterChef = IMasterChef(_masterChef); emit ChangedAddress("MASTER_CHEF", address(0), _masterChef); startBlock = _startBlock == 0 ? block.number : _startBlock; emit SetRewardsStartBlock(startBlock); rewardTokensPerBlock = _rewardTokensPerBlock; emit ChangedRewardTokensPerBlock(0, _rewardTokensPerBlock); rewardToken.safeIncreaseAllowance(address(vault), type(uint256).max); } /** * @notice View function to see current poolInfo array length * @return pool length */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Add a new reward token to the pool * @dev Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. * @param allocPoint Number of allocation points to allot to this token/pool * @param token The token that will be staked for rewards * @param vestingPercent The percentage of rewards from this pool that will vest * @param vestingPeriod The number of days for the vesting period * @param vestingCliff The number of days for the vesting cliff * @param withUpdate if specified, update all pools before adding new pool * @param sushiPid The pid of the Sushiswap pool in the Masterchef contract (if exists, otherwise provide zero) * @param vpForDeposit If true, users get voting power for deposits * @param vpForVesting If true, users get voting power for vesting balances */ function add( uint256 allocPoint, address token, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool withUpdate, uint256 sushiPid, bool vpForDeposit, bool vpForVesting ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + allocPoint; poolInfo.push(PoolInfo({ token: IERC20Extended(token), allocPoint: allocPoint, lastRewardBlock: rewardStartBlock, accRewardsPerShare: 0, vestingPercent: vestingPercent, vestingPeriod: vestingPeriod, vestingCliff: vestingCliff, totalStaked: 0, vpForDeposit: vpForDeposit, vpForVesting: vpForVesting })); if (sushiPid != uint256(0)) { sushiPools[token] = sushiPid; IERC20Extended(token).safeIncreaseAllowance(address(masterChef), type(uint256).max); } IERC20Extended(token).safeIncreaseAllowance(address(vault), type(uint256).max); emit PoolAdded(poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartBlock, sushiPid, vpForDeposit, vpForVesting); } /** * @notice Update the given pool's allocation points * @dev Can only be called by the owner * @param pid The RewardManager pool id * @param allocPoint New number of allocation points for pool * @param withUpdate if specified, update all pools before setting allocation points */ function set( uint256 pid, uint256 allocPoint, bool withUpdate ) external onlyOwner { if (withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[pid].allocPoint + allocPoint; emit PoolUpdated(pid, poolInfo[pid].allocPoint, allocPoint, totalAllocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Returns true if rewards are actively being accumulated */ function rewardsActive() public view returns (bool) { return block.number >= startBlock && totalAllocPoint > 0 ? true : false; } /** * @notice Return reward multiplier over the given from to to block. * @param from From block number * @param to To block number * @return multiplier */ function getMultiplier(uint256 from, uint256 to) public pure returns (uint256) { return to > from ? to - from : 0; } /** * @notice View function to see pending reward tokens on frontend. * @param pid pool id * @param account user account to check * @return pending rewards */ function pendingRewardTokens(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 tokenSupply = pool.totalStaked; if (block.number > pool.lastRewardBlock && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; accRewardsPerShare = accRewardsPerShare + totalReward * 1e12 / tokenSupply; } uint256 accumulatedRewards = user.amount * accRewardsPerShare / 1e12; if (accumulatedRewards < user.rewardTokenDebt) { return 0; } return accumulatedRewards - user.rewardTokenDebt; } /** * @notice View function to see pending SUSHI on frontend. * @param pid pool id * @param account user account to check * @return pending SUSHI rewards */ function pendingSushi(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid == uint256(0)) { return 0; } IMasterChef.PoolInfo memory sushiPool = masterChef.poolInfo(sushiPid); uint256 sushiPerBlock = masterChef.sushiPerBlock(); uint256 totalSushiAllocPoint = masterChef.totalAllocPoint(); uint256 accSushiPerShare = sushiPool.accSushiPerShare; uint256 lpSupply = sushiPool.lpToken.balanceOf(address(masterChef)); if (block.number > sushiPool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = masterChef.getMultiplier(sushiPool.lastRewardBlock, block.number); uint256 sushiReward = multiplier * sushiPerBlock * sushiPool.allocPoint / totalSushiAllocPoint; accSushiPerShare = accSushiPerShare + sushiReward * 1e12 / lpSupply; } uint256 accumulatedSushi = user.amount * accSushiPerShare / 1e12; if (accumulatedSushi < user.sushiRewardDebt) { return 0; } return accumulatedSushi - user.sushiRewardDebt; } /** * @notice Update reward variables for all pools * @dev Be careful of gas spending! */ function massUpdatePools() public { for (uint256 pid = 0; pid < poolInfo.length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param pid pool id */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 tokenSupply = pool.totalStaked; if (tokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; pool.accRewardsPerShare = pool.accRewardsPerShare + totalReward * 1e12 / tokenSupply; pool.lastRewardBlock = block.number; } /** * @notice Deposit tokens to RewardsManager for rewards allocation. * @param pid pool id * @param amount number of tokens to deposit */ function deposit(uint256 pid, uint256 amount) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _deposit(pid, amount, pool, user); } /** * @notice Deposit tokens to RewardsManager for rewards allocation, using permit for approval * @dev It is up to the frontend developer to ensure the pool token implements permit - otherwise this will fail * @param pid pool id * @param amount number of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit( uint256 pid, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.token.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(pid, amount, pool, user); } /** * @notice Withdraw tokens from RewardsManager, claiming rewards. * @param pid pool id * @param amount number of tokens to withdraw */ function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, "RM::withdraw: amount must be > 0"); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool id */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.withdraw(sushiPid, user.amount); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), user.amount); } pool.totalStaked = pool.totalStaked - user.amount; pool.token.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewardTokenDebt = 0; user.sushiRewardDebt = 0; } } /** * @notice Set approvals for external addresses to use contract tokens * @dev Can only be called by the owner * @param tokensToApprove the tokens to approve * @param approvalAmounts the token approval amounts * @param spender the address to allow spending of token */ function tokenAllow( address[] memory tokensToApprove, uint256[] memory approvalAmounts, address spender ) external onlyOwner { require(tokensToApprove.length == approvalAmounts.length, "RM::tokenAllow: not same length"); for(uint i = 0; i < tokensToApprove.length; i++) { IERC20Extended token = IERC20Extended(tokensToApprove[i]); if (token.allowance(address(this), spender) != type(uint256).max) { token.safeApprove(spender, approvalAmounts[i]); } } } /** * @notice Rescue (withdraw) tokens from the smart contract * @dev Can only be called by the owner * @param tokens the tokens to withdraw * @param amounts the amount of each token to withdraw. If zero, withdraws the maximum allowed amount for each token * @param receiver the address that will receive the tokens */ function rescueTokens( address[] calldata tokens, uint256[] calldata amounts, address receiver ) external onlyOwner { require(tokens.length == amounts.length, "RM::rescueTokens: not same length"); for (uint i = 0; i < tokens.length; i++) { IERC20Extended token = IERC20Extended(tokens[i]); uint256 withdrawalAmount; uint256 tokenBalance = token.balanceOf(address(this)); uint256 tokenAllowance = token.allowance(address(this), receiver); if (amounts[i] == 0) { if (tokenBalance > tokenAllowance) { withdrawalAmount = tokenAllowance; } else { withdrawalAmount = tokenBalance; } } else { require(tokenBalance >= amounts[i], "RM::rescueTokens: contract balance too low"); require(tokenAllowance >= amounts[i], "RM::rescueTokens: increase token allowance"); withdrawalAmount = amounts[i]; } token.safeTransferFrom(address(this), receiver, withdrawalAmount); } } /** * @notice Set new rewards per block * @dev Can only be called by the owner * @param newRewardTokensPerBlock new amount of reward token to reward each block */ function setRewardsPerBlock(uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedRewardTokensPerBlock(rewardTokensPerBlock, newRewardTokensPerBlock); rewardTokensPerBlock = newRewardTokensPerBlock; } /** * @notice Set new SUSHI token address * @dev Can only be called by the owner * @param newToken address of new SUSHI token */ function setSushiToken(address newToken) external onlyOwner { emit ChangedAddress("SUSHI_TOKEN", address(sushiToken), newToken); sushiToken = IERC20Extended(newToken); } /** * @notice Set new MasterChef address * @dev Can only be called by the owner * @param newAddress address of new MasterChef */ function setMasterChef(address newAddress) external onlyOwner { emit ChangedAddress("MASTER_CHEF", address(masterChef), newAddress); masterChef = IMasterChef(newAddress); } /** * @notice Set new Vault address * @param newAddress address of new Vault */ function setVault(address newAddress) external onlyOwner { emit ChangedAddress("VAULT", address(vault), newAddress); vault = IVault(newAddress); } /** * @notice Set new LockManager address * @param newAddress address of new LockManager */ function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } /** * @notice Change owner of Rewards Manager contract * @dev Can only be called by the owner * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "RM::changeOwner: not valid address"); emit ChangedOwner(owner, newOwner); owner = newOwner; } /** * @notice Internal implementation of deposit * @param pid pool id * @param amount number of tokens to deposit * @param pool the pool info * @param user the user info */ function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; uint256 pendingSushiTokens = 0; if (user.amount > 0) { uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked + amount; user.amount = user.amount + amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); user.sushiRewardDebt = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; masterChef.deposit(sushiPid, amount); } if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } emit Deposit(msg.sender, pid, amount); } /** * @notice Internal implementation of withdraw * @param pid pool id * @param amount number of tokens to withdraw * @param pool the pool info * @param user the user info */ function _withdraw( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { require(user.amount >= amount, "RM::_withdraw: amount > user balance"); updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); uint256 pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; masterChef.withdraw(sushiPid, amount); user.sushiRewardDebt = (user.amount - amount) * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } } uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; user.amount = user.amount - amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), amount); } pool.totalStaked = pool.totalStaked - amount; pool.token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } /** * @notice Internal function used to distribute rewards, optionally vesting a % * @param account account that is due rewards * @param rewardAmount amount of rewards to distribute * @param vestingPercent percent of rewards to vest in bips * @param vestingPeriod number of days over which to vest rewards * @param vestingCliff number of days for vesting cliff * @param vestingVotingPower if true, grant voting power for vesting balance */ function _distributeRewards( address account, uint256 rewardAmount, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool vestingVotingPower ) internal { uint256 vestingRewards = rewardAmount * vestingPercent / 1000000; rewardToken.mint(address(this), rewardAmount); vault.lockTokens(address(rewardToken), address(this), account, 0, vestingRewards, vestingPeriod, vestingCliff, vestingVotingPower); rewardToken.safeTransfer(msg.sender, rewardAmount - vestingRewards); } /** * @notice Safe SUSHI transfer function, just in case if rounding error causes pool to not have enough SUSHI. * @param to account that is receiving SUSHI * @param amount amount of SUSHI to send */ function _safeSushiTransfer(address to, uint256 amount) internal { uint256 sushiBalance = sushiToken.balanceOf(address(this)); if (amount > sushiBalance) { sushiToken.safeTransfer(to, sushiBalance); } else { sushiToken.safeTransfer(to, amount); } } } // 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"; interface IERC20Burnable is IERC20 { function burn(uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Metadata.sol"; import "./IERC20Mintable.sol"; import "./IERC20Burnable.sol"; import "./IERC20Permit.sol"; import "./IERC20TransferWithAuth.sol"; import "./IERC20SafeAllowance.sol"; interface IERC20Extended is IERC20Metadata, IERC20Mintable, IERC20Burnable, IERC20Permit, IERC20TransferWithAuth, IERC20SafeAllowance {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; 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; import "./IERC20.sol"; interface IERC20Mintable is IERC20 { function mint(address dst, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Permit is IERC20 { function getDomainSeparator() external view returns (bytes32); function DOMAIN_TYPEHASH() external view returns (bytes32); function VERSION_HASH() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function nonces(address) external view returns (uint); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20SafeAllowance is IERC20 { function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20TransferWithAuth is IERC20 { function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ILockManager { struct LockedStake { uint256 amount; uint256 votingPower; } function getAmountStaked(address staker, address stakedToken) external view returns (uint256); function getStake(address staker, address stakedToken) external view returns (LockedStake memory); function calculateVotingPower(address token, uint256 amount) external view returns (uint256); function grantVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerGranted); function removeVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerRemoved); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IMasterChef { struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. } function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function updatePool(uint256 _pid) external; function sushiPerBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IVault { struct Lock { address token; address receiver; uint48 startTime; uint16 vestingDurationInDays; uint16 cliffDurationInDays; uint256 amount; uint256 amountClaimed; uint256 votingPower; } struct LockBalance { uint256 id; uint256 claimableAmount; Lock lock; } struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; uint256 votingPower; } function lockTokens(address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 lockDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower) external; function lockTokensWithPermit(address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 lockDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function claimUnlockedTokenAmounts(uint256[] memory lockIds, uint256[] memory amounts) external; function claimAllUnlockedTokens(uint256[] memory lockIds) external; function tokenLocks(uint256 lockId) external view returns(Lock memory); function allActiveLockIds() external view returns(uint256[] memory); function allActiveLocks() external view returns(Lock[] memory); function allActiveLockBalances() external view returns(LockBalance[] memory); function activeLockIds(address receiver) external view returns(uint256[] memory); function allLocks(address receiver) external view returns(Lock[] memory); function activeLocks(address receiver) external view returns(Lock[] memory); function activeLockBalances(address receiver) external view returns(LockBalance[] memory); function totalTokenBalance(address token) external view returns(TokenBalance memory balance); function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance); function lockBalance(uint256 lockId) external view returns (LockBalance memory); function claimableBalance(uint256 lockId) external view returns (uint256); function extendLock(uint256 lockId, uint16 vestingDaysToAdd, uint16 cliffDaysToAdd) external; } // 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; 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' 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"); } } }
* @notice View function to see pending SUSHI on frontend. @param pid pool id @param account user account to check @return pending SUSHI rewards/
function pendingSushi(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid == uint256(0)) { return 0; } IMasterChef.PoolInfo memory sushiPool = masterChef.poolInfo(sushiPid); uint256 sushiPerBlock = masterChef.sushiPerBlock(); uint256 totalSushiAllocPoint = masterChef.totalAllocPoint(); uint256 accSushiPerShare = sushiPool.accSushiPerShare; uint256 lpSupply = sushiPool.lpToken.balanceOf(address(masterChef)); if (block.number > sushiPool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = masterChef.getMultiplier(sushiPool.lastRewardBlock, block.number); uint256 sushiReward = multiplier * sushiPerBlock * sushiPool.allocPoint / totalSushiAllocPoint; accSushiPerShare = accSushiPerShare + sushiReward * 1e12 / lpSupply; } uint256 accumulatedSushi = user.amount * accSushiPerShare / 1e12; if (accumulatedSushi < user.sushiRewardDebt) { return 0; } return accumulatedSushi - user.sushiRewardDebt; }
212,314
[ 1, 1767, 445, 358, 2621, 4634, 11726, 2664, 45, 603, 15442, 18, 225, 4231, 2845, 612, 225, 2236, 729, 2236, 358, 866, 327, 4634, 11726, 2664, 45, 283, 6397, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4634, 55, 1218, 77, 12, 11890, 5034, 4231, 16, 1758, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 6610, 6362, 4631, 15533, 203, 3639, 2254, 5034, 272, 1218, 77, 12478, 273, 272, 1218, 77, 16639, 63, 2867, 12, 6011, 18, 2316, 13, 15533, 203, 3639, 309, 261, 87, 1218, 77, 12478, 422, 2254, 5034, 12, 20, 3719, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 6246, 2440, 39, 580, 74, 18, 2864, 966, 3778, 272, 1218, 77, 2864, 273, 4171, 39, 580, 74, 18, 6011, 966, 12, 87, 1218, 77, 12478, 1769, 203, 3639, 2254, 5034, 272, 1218, 77, 2173, 1768, 273, 4171, 39, 580, 74, 18, 87, 1218, 77, 2173, 1768, 5621, 203, 3639, 2254, 5034, 2078, 55, 1218, 77, 8763, 2148, 273, 4171, 39, 580, 74, 18, 4963, 8763, 2148, 5621, 203, 3639, 2254, 5034, 4078, 55, 1218, 77, 2173, 9535, 273, 272, 1218, 77, 2864, 18, 8981, 55, 1218, 77, 2173, 9535, 31, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 272, 1218, 77, 2864, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 7525, 39, 580, 74, 10019, 203, 3639, 309, 261, 2629, 18, 2696, 405, 272, 1218, 77, 2864, 18, 2722, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 4171, 39, 580, 74, 18, 588, 23365, 12, 87, 1218, 77, 2864, 18, 2722, 2 ]
./full_match/84531/0xC960aA9E4F685421638379Baa47Be0f1F2dfe7C6/sources/contracts/JetStakingV1.sol
Stream didn't start
if (block.timestamp <= streamStart) return 0;
11,505,729
[ 1, 1228, 10242, 1404, 787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 2629, 18, 5508, 1648, 1407, 1685, 13, 327, 374, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /** * @title BT **/ interface tokenTransfer { function totalSupply() external view returns (uint256); function balanceOf(address receiver) external returns(uint256); function transfer(address receiver, uint amount) external; function transferFrom(address _from, address _to, uint256 _value) external; function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); } contract Util { uint usdtWei = 1e6; //��̬���� function getRecommendScaleByAmountAndTim(uint performance,uint times) internal view returns(uint){ if (times == 1) { return 18; } if(performance >= 2000*usdtWei && performance < 6000*usdtWei){ if (times == 2){ return 10; } if(times == 3){ return 8; } } if(performance >= 6000*usdtWei && performance < 10000*usdtWei){ if (times == 2){ return 10; } if(times == 3){ return 8; } if(times == 4){ return 5; } if(times >= 5 && times <= 10){ return 4; } } if(performance >= 10000*usdtWei && performance < 20000*usdtWei){ if (times == 2){ return 10; } if(times == 3){ return 8; } if(times == 4){ return 5; } if(times >= 5 && times <= 15){ return 4; } } if(performance >= 20000*usdtWei){ if (times == 2){ return 10; } if(times == 3){ return 8; } if(times == 4){ return 5; } if(times >= 5 && times <= 15){ return 4; } if(times >= 16 && times <= 20){ return 3; } } return 0; } //PK���� function getAward(uint times) internal pure returns(uint){ if (times == 1) { return 35; } if(times == 2){ return 25; } if(times == 3){ return 20; } if(times == 4){ return 12; } if(times == 5){ return 8; } return 0; } //�û��ȼ� function getDynLevel(uint myPerformance,uint hashratePerformance) internal view returns(uint) { if (myPerformance < 2000 * usdtWei || hashratePerformance < 2000 * usdtWei) { return 0; } if (hashratePerformance >= 2000 * usdtWei && hashratePerformance < 30000 * usdtWei) { return 1; } if (hashratePerformance >= 30000 * usdtWei && hashratePerformance < 200000 * usdtWei) { return 2; } if (hashratePerformance >= 200000 * usdtWei && hashratePerformance < 500000 * usdtWei) { return 3; } if (hashratePerformance >= 500000 * usdtWei) { return 4; } return 0; } function compareStr(string memory _str, string memory str) internal pure returns(bool) { if (keccak256(abi.encodePacked(_str)) == keccak256(abi.encodePacked(str))) { return true; } return false; } } /* * @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) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context, Ownable { using Roles for Roles.Role; Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelist(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelist(_msgSender()) || isOwner(), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function addWhitelist(address account) public onlyWhitelistAdmin { _addWhitelist(account); } function removeWhitelist(address account) public onlyOwner { _whitelistAdmins.remove(account); } function isWhitelist(address account) private view returns (bool) { return _whitelistAdmins.has(account); } function _addWhitelist(address account) internal { _whitelistAdmins.add(account); } } contract CoinTokenWrapper { using SafeMath for *; uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) internal { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); } } contract BtPro is Util, WhitelistAdminRole,CoinTokenWrapper { string constant private name = "Bt Pro"; struct User{ uint id; string referrer; uint dynamicLevel; uint allInvest; uint freezeAmount; uint allDynamicAmount; uint hisDynamicAmount; //Game uint hisGameAmount; //�ҵ�ֱ��ҵ�� uint performance; //������ҵ�� uint nodePerformance; Invest[] invests; uint staticFlag; //������ҵ�� uint hashratePerformance; //BT�ڿ��ܽ��� uint hisBtAward; //vipδ�ֺ콱�� uint256 vipBonus; //vip�ۼƷֺ� uint256 vipTotalBonus; //���� uint checkpoint; } struct UserGlobal { uint id; address userAddress; string inviteCode; string referrer; } struct Invest{ uint investAmount; uint limitAmount; uint earnAmount; } struct BigRound { uint gameAmount; } //24h ȫ��ھ� struct GlobalChampion { address userAddress; uint performance; } uint startTime; uint endTime; uint investMoney; uint residueMoney; uint uid = 0; uint rid = 1; uint period = 12 hours; uint statisticsDay; uint statisticsTwoCount = 0; uint statisticsTwoDay; uint gameRate = 20000; mapping (uint => mapping(address => User)) userRoundMapping; mapping(address => UserGlobal) userMapping; mapping (string => address) addressMapping; mapping (uint => address) indexMapping; //============================================================================== address payable destructionAddr = address(0xaC772670397Ab85D0d7A8C0E60acc4150a05088E); address payable coinPriceAddr = address(0x009e7a1a26A6DCcDC347F00B5Fac14241C66a783); address payable marketAddr = address(0x63b79A83ECafAE19D19517A8F88263f7511137d3); address uToken = address(0xa614f803B6FD780986A42c78Ec9c7f77e6DeD13C); tokenTransfer u = tokenTransfer(uToken); GlobalChampion[] globalChampionArr; //��0 ��1 uint gameSwitch = 0; uint bigRid = 1; mapping (uint256 => BigRound) bigRound; modifier isHuman() { address addr = msg.sender; uint codeLength; assembly {codeLength := extcodesize(addr)} require(codeLength == 0, "sorry humans only"); require(tx.origin == msg.sender, "sorry, human only"); _; } event LogInvestIn(address indexed who, uint indexed uid, uint amount, uint time, string inviteCode, string referrer); event LogWithdrawProfit(address indexed who, uint indexed uid, uint amount, uint time); event LogGameWinner(address indexed who, uint amount, uint time,string gameType); event UserLevel(address indexed user,uint256 p, uint256 level); event LogPullUpPrices(address user,uint256 amt); //============================================================================== // Constructor //============================================================================== constructor () public { startTime = now; endTime = startTime.add(period); } function () external payable { } //Ͷ�� function investIn(string memory inviteCode,string memory referrer,uint256 value) public updateReward(msg.sender) checkStart checkhalve isHuman() { require(value >= 21*usdtWei, "The minimum bet is 21 USDT"); require(value <= 210000*usdtWei, "The biggest bet is 210000 USDT"); require(value == value.div(usdtWei).mul(usdtWei), "invalid msg value"); u.transferFrom(msg.sender,address(this),value); UserGlobal storage userGlobal = userMapping[msg.sender]; if (userGlobal.id == 0) { require(!compareStr(inviteCode, ""), "empty invite code"); address referrerAddr = getUserAddressByCode(referrer); require(uint(referrerAddr) != 0, "referer not exist"); require(referrerAddr != msg.sender, "referrer can't be self"); require(!isUsed(inviteCode), "invite code is used"); registerUser(msg.sender, inviteCode, referrer); } //�Ƿ������û� User storage user = userRoundMapping[rid][msg.sender]; if (user.id != 0) { user.allInvest = user.allInvest.add(value); user.freezeAmount = user.freezeAmount.add(value); } else { user.id = userGlobal.id; user.freezeAmount = value; user.allInvest = value; user.referrer = userGlobal.referrer; } //Ǯ���Ŵ����� Invest memory invest = Invest(value, value.mul(3), 0); user.invests.push(invest); investMoney = investMoney.add(value); statisticsDay = statisticsDay.add(value); //�û���̬�����Զ��ֺ� tjUserDynamicTree(userGlobal.referrer,value); //ͳ��ÿ������ statisticOfDay(); //ͳ��ֱ�ƹھ�ҵ�� statisticOfChampion(getUserAddressByCode(referrer),value); //40%�ڿ� fixedDepositMining(value); //�ڿ� super.stake(value); emit LogInvestIn(msg.sender, userGlobal.id, value, now, userGlobal.inviteCode, userGlobal.referrer); } //ͳ���û��ڵ� function tjUserDynamicTree(string memory referrer, uint investAmount) private { string memory tmpReferrer = referrer; uint dynAmt = investAmount.mul(50).div(100); uint totalTmpAmount; for (uint i = 1; i <= 20; i++) { if (compareStr(tmpReferrer, "")) { break; } address tmpUserAddr = addressMapping[tmpReferrer]; User storage calUser = userRoundMapping[rid][tmpUserAddr]; if (calUser.id == 0) { break; } //����ϼ��ѿյ��������� if(calUser.freezeAmount <= 0){ tmpReferrer = calUser.referrer; continue; } //ͳ��2���ڵ�������ҵ�� if(i == 1 || i == 2){ //ͳ��1��������ڵ�ҵ�� if(i == 1){ calUser.performance = calUser.performance.add(investAmount); } calUser.nodePerformance = calUser.nodePerformance.add(investAmount); } //����������� uint recommendSc = getRecommendScaleByAmountAndTim(calUser.nodePerformance, i); if (recommendSc != 0) { //ͳ������������ calUser.hashratePerformance = calUser.hashratePerformance.add(investAmount); //���� uint tmpDynamicAmount = dynAmt.mul(recommendSc).div(100); Invest storage invest = calUser.invests[calUser.staticFlag]; invest.earnAmount = invest.earnAmount.add(tmpDynamicAmount); //�����ж� if (invest.earnAmount >= invest.limitAmount) { calUser.staticFlag = calUser.staticFlag.add(1); calUser.freezeAmount = calUser.freezeAmount.sub(invest.investAmount); //�������� uint correction = invest.earnAmount.sub(invest.limitAmount); if(correction > 0){ tmpDynamicAmount = tmpDynamicAmount.sub(correction); invest.earnAmount = invest.limitAmount; } } //�ۼ��û����� calUser.allDynamicAmount = calUser.allDynamicAmount.add(tmpDynamicAmount); calUser.hisDynamicAmount = calUser.hisDynamicAmount.add(tmpDynamicAmount); totalTmpAmount = totalTmpAmount.add(tmpDynamicAmount); } tmpReferrer = calUser.referrer; } //������ʽ���䵽40%��ַ residueMoney = residueMoney.add(dynAmt.sub(totalTmpAmount)); } //ͳ��ÿ������ function statisticOfDay() private { if(getTimeLeft() != 0){ return; } //update time startTime = endTime; endTime = startTime.add(period); //��Ϸ���� if(gameSwitch == 1){ //����10% uint awardAmount = bigRound[bigRid].gameAmount.mul(10).div(100); if(awardAmount > 1 * usdtWei){ //Top5���� (address[5] memory ads,,uint[5] memory awards) = pkRanking(); uint topLen = ads.length; for(uint i = 0;i<topLen;i++){ uint a = awards[i]; if(a > 0){ //���а��� uint topAwar = awardAmount.mul(a).div(100); winnerAward(ads[i],topAwar,"King"); } } //���½������� bigRound[bigRid].gameAmount = bigRound[bigRid].gameAmount.sub(awardAmount); } //���ֱ�ƹھ����� globalChampionArr.length = 0; //48Сʱ���� statisticsTwoDay = statisticsTwoDay.add(statisticsDay); statisticsTwoCount = statisticsTwoCount.add(1); if(statisticsTwoCount >= 2){ //����½��ʽ��Ƿ����10��U if(statisticsTwoDay <= gameRate * usdtWei){ pullUpPrices(); } statisticsTwoDay = 0; statisticsTwoCount = 0; } statisticsDay = 0; } //����ֺ� settlementBonus(); } //ֱ�ƹھ�ͳ�� function statisticOfChampion(address _sender,uint _value) private { //pk 10% bigRound[bigRid].gameAmount = bigRound[bigRid].gameAmount.add(_value.mul(10).div(100)); if(uint(_sender) == 0){ return; } if(gameSwitch == 1){ uint addrIndex = getChampionIndex(globalChampionArr,_sender); if(addrIndex == 1000000){ GlobalChampion memory cg = GlobalChampion(_sender,_value); globalChampionArr.push(cg); } else { GlobalChampion storage cg = globalChampionArr[addrIndex]; cg.performance = cg.performance.add(_value); } } } function getChampionIndex(GlobalChampion[] memory a,address _address) internal pure returns (uint) { uint256 length = a.length; for(uint i = 0; i < length; i++) { if(a[i].userAddress == _address){ return i; } } return 1000000; } function pkCompare(address[] memory _top) internal view returns (uint,address) { uint max; address userAddress; for(uint i = 0; i < globalChampionArr.length; i++) { if(globalChampionArr[i].performance > max){ uint flag = 0; //check for(uint j = 0; j < _top.length;j++){ if(globalChampionArr[i].userAddress == _top[j]){ flag = 1; break; } } if(flag == 0){ max = globalChampionArr[i].performance; userAddress = globalChampionArr[i].userAddress; } } } return (max,userAddress); } function pkRanking() public view returns (address[5] memory ads,uint[5] memory cts,uint[5] memory awards) { address[] memory tops = new address[](5); for(uint i = 0; i<5; i++){ (uint top,address topAddress) = pkCompare(tops); if(top == 0){ break; } tops[i] = topAddress; cts[i] = top; ads[i] = topAddress; awards[i] = getAward(i+1); } return (ads,cts,awards); } //����USDT function withdrawProfit() updateReward(msg.sender) checkhalve checkIncreaseCoin public { User storage user = userRoundMapping[rid][msg.sender]; require(user.id > 0, "user not exist"); statisticOfDay(); uint resultMoney = user.allDynamicAmount; if (resultMoney > 0) { //��U takeInner(msg.sender,resultMoney); user.allDynamicAmount = 0; emit LogWithdrawProfit(msg.sender, user.id, resultMoney, now); } //������ upDynamicLevel(); } //�����Ҽ� function pullUpPrices() private { uint destructionAmountAmount = bigRound[bigRid].gameAmount.mul(10).div(100); if(destructionAmountAmount > 1 * usdtWei){ //תU takeInner(coinPriceAddr,destructionAmountAmount); //���½������� bigRound[bigRid].gameAmount = bigRound[bigRid].gameAmount.sub(destructionAmountAmount); emit LogPullUpPrices(coinPriceAddr,destructionAmountAmount); } } //�г����� function marketIncentives() public { uint resultMoney = residueMoney; //תU takeInner(marketAddr,resultMoney); //���ʣ���ʽ� residueMoney = 0; emit LogPullUpPrices(marketAddr,resultMoney); } //�ڿ� function fixedDepositMining(uint256 money) private { uint miningAmount = money.mul(40).div(100); //תU takeInner(destructionAddr,miningAmount); } //�����û��ȼ� function upDynamicLevel() private { User storage calUser = userRoundMapping[rid][msg.sender]; uint dynamicLevel = calUser.dynamicLevel; uint newDynLevel = getDynLevel(calUser.performance,calUser.hashratePerformance); if(newDynLevel != 0 && dynamicLevel != newDynLevel){ //update checkpoint if(calUser.checkpoint == 0){ calUser.checkpoint = shareBonusCount; } //��ȡ�ֺ� useStatisticalBonusInner(); //up level calUser.dynamicLevel = newDynLevel; //�Ƴ�ԭ��&�����û� doRemoveVip(calUser.id,dynamicLevel); doAddVip(calUser.id,newDynLevel); emit UserLevel(msg.sender,calUser.hashratePerformance,newDynLevel); } } //����� function isEnoughBalance(uint sendMoney) private returns (bool, uint){ uint _balance = u.balanceOf(address(this)); if (sendMoney >= _balance) { return (false, _balance); } else { return (true, sendMoney); } } //ȡǮ function takeInner(address payable userAddress, uint money) private { uint sendMoney; (, sendMoney) = isEnoughBalance(money); if (sendMoney > 0) { u.transfer(userAddress,sendMoney); } } function isUsed(string memory code) public view returns(bool) { address user = getUserAddressByCode(code); return uint(user) != 0; } function getUserAddressByCode(string memory code) public view returns(address) { return addressMapping[code]; } function getMiningInfo(address _user) public view returns(uint[44] memory ct,string memory inviteCode, string memory referrer) { User memory userInfo = userRoundMapping[rid][_user]; uint256 earned = earned(_user); ct[0] = totalSupply(); ct[1] = turnover; ct[2] = userInfo.hashratePerformance; ct[3] = userInfo.hisBtAward; ct[4] = userInfo.dynamicLevel; ct[5] = earned; ct[6] = status; ct[7] = bonusPool; ct[8] = vipTodayBonus[0]; ct[9] = vipTodayBonus[1]; ct[10] = vipTodayBonus[2]; ct[11] = vipTodayBonus[3]; ct[12] = vipHisBonus[0]; ct[13] = vipHisBonus[1]; ct[14] = vipHisBonus[2]; ct[15] = vipHisBonus[3]; ct[16] = vipLength[0]; ct[17] = vipLength[1]; ct[18] = vipLength[2]; ct[19] = vipLength[3]; ct[20] = unWithdrawBonus(_user); ct[21] = basicCoin; ct[22] = increaseNumber; ct[23] = userInfo.vipBonus; ct[24] = userInfo.vipTotalBonus; ct[25] = userInfo.checkpoint; //Game INFO ct[26] = endTime; ct[27] = getTimeLeft(); ct[28] = investMoney; ct[29] = residueMoney; ct[30] = gameSwitch; //USER INFO ct[31] = userInfo.dynamicLevel; ct[32] = userInfo.allInvest; ct[33] = userInfo.freezeAmount; ct[34] = userInfo.allDynamicAmount; ct[35] = userInfo.hisDynamicAmount; ct[36] = userInfo.staticFlag; ct[37] = userInfo.invests.length; ct[38] = userInfo.performance; ct[39] = userInfo.hisGameAmount; ct[40] = userInfo.nodePerformance; ct[41] = periodFinish; ct[42] = bigRid; ct[43] = bigRound[bigRid].gameAmount; inviteCode = userMapping[_user].inviteCode; referrer = userMapping[_user].referrer; return ( ct, inviteCode, referrer ); } function getUserAssetInfo(address user, uint i) public view returns( uint[5] memory ct ) { User memory userInfo = userRoundMapping[rid][user]; ct[0] = userInfo.invests.length; if (ct[0] != 0) { ct[1] = userInfo.invests[i].investAmount; ct[2] = userInfo.invests[i].limitAmount; ct[3] = userInfo.invests[i].earnAmount; ct[4] = 0; } else { ct[1] = 0; ct[2] = 0; ct[3] = 0; ct[4] = 0; } } function activeGame(uint time) external onlyWhitelistAdmin { require(time > now, "invalid game start time"); startTime = time; endTime = startTime.add(period); } function correctionStatistics() external onlyWhitelistAdmin { statisticOfDay(); } function changeGameSwitch(uint _gameSwitch) external onlyWhitelistAdmin { gameSwitch = _gameSwitch; } function changeGameRate(uint _gameRate) external onlyWhitelistAdmin { gameRate = _gameRate; } function clearChampion() external onlyWhitelistAdmin { //���ֱ�ƹھ����� globalChampionArr.length = 0; } function getTimeLeft() private view returns(uint256) { // grab time uint256 _now = now; if (_now < endTime) if (_now > startTime) return( endTime.sub(_now)); else return( (startTime).sub(_now)); else return(0); } //��ϷӮ�ҽ��� function winnerAward(address _address,uint sendMoney,string memory gameType) private { User storage calUser = userRoundMapping[rid][_address]; if(calUser.freezeAmount <= 0){ emit LogGameWinner(_address,sendMoney,now,gameType); return; } calUser.hisGameAmount = calUser.hisGameAmount.add(sendMoney); address payable sendAddr = address(uint160(_address)); takeInner(sendAddr,sendMoney); emit LogGameWinner(sendAddr,sendMoney,now,gameType); } function registerUserInfo(address user, string calldata inviteCode, string calldata referrer) external onlyOwner { registerUser(user, inviteCode, referrer); } function registerUser(address user, string memory inviteCode, string memory referrer) private { UserGlobal storage userGlobal = userMapping[user]; uid++; userGlobal.id = uid; userGlobal.userAddress = user; userGlobal.inviteCode = inviteCode; userGlobal.referrer = referrer; addressMapping[inviteCode] = user; indexMapping[uid] = user; } //------------------------------�ڿ��߼� uint256 turnover; uint256 bonusPool; address btTokenAddr = address(0x89803bED482520Df00Eb634c6477dA20E3Bf6E61); tokenTransfer btToken = tokenTransfer(btTokenAddr); //Ϊ0����ͷ��Ϊ1�������� uint256 status = 0; //utc+8 2021-03-12 19:41:05 uint256 public starttime = 1615549265; //�ڿ����ʱ�� uint256 public periodFinish = 0; //�������� uint256 public rewardRate = 0; //������ʱ�� uint256 public lastUpdateTime; //ÿ���洢�����ƽ��� uint256 public rewardPerTokenStored; //ÿ֧��һ�����ҵ��û����� mapping(address => uint256) public userRewardPerTokenPaid; //�û����� mapping(address => uint256) public rewards; //---------------------------------global vip struct Bonus { uint256 vip1AvgBonus; uint256 vip2AvgBonus; uint256 vip3AvgBonus; uint256 vip4AvgBonus; } //�ֺ���� uint256 public shareBonusCount = 1; //����� mapping (uint => Bonus) public gifts; //uid -> 1 mapping (uint => uint) vip1s; mapping (uint => uint) vip2s; mapping (uint => uint) vip3s; mapping (uint => uint) vip4s; //��̬������� uint256[] bonusRate = [18,10,7,5]; //vip���ս��� uint256[] public vipTodayBonus = [0,0,0,0]; //vip��ʷ���� uint256[] public vipHisBonus = [0,0,0,0]; //vip���� uint256[] public vipLength = [0,0,0,0]; event RewardAdded(uint256 reward); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return SafeMath.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } //��ȡBT function getReward() public updateReward(msg.sender) checkhalve checkIncreaseCoin { User storage user = userRoundMapping[rid][msg.sender]; require(user.id > 0, "user not exist"); statisticOfDay(); uint256 reward = earned(msg.sender); if (reward > 0) { uint staticReward = reward.mul(60).div(100); //�ۼ��û���̬�ڿ����� user.hisBtAward = user.hisBtAward.add(staticReward); //��ͨ�� turnover = turnover.add(staticReward); rewards[msg.sender] = 0; btToken.transfer(msg.sender, staticReward); emit RewardPaid(msg.sender, staticReward); //vip����� uint dynReward = reward.mul(40).div(100); bonusPool = bonusPool.add(dynReward); //��̬�ֺ��ۼ� for(uint i = 0;i<bonusRate.length;i++){ uint amt = reward.mul(bonusRate[i]).div(100); vipTodayBonus[i] = vipTodayBonus[i].add(amt); vipHisBonus[i] = vipHisBonus[i].add(amt); } } //������ upDynamicLevel(); } //����24Сʱ�ֺ콱�� function settlementBonus() private { //�����ܽ��� / vip���� = ƽ���ֺ콱�� for(uint i = 0;i<vipTodayBonus.length;i++){ uint todayBonus = vipTodayBonus[i]; if(todayBonus == 0){ break; } uint length = vipLength[i]; if(length == 0){ length = 1; } uint256 avgBonus = todayBonus.div(length); if(i == 0){ gifts[shareBonusCount].vip1AvgBonus = avgBonus; }else if(i == 1){ gifts[shareBonusCount].vip2AvgBonus = avgBonus; }else if(i == 2){ gifts[shareBonusCount].vip3AvgBonus = avgBonus; }else if(i == 3){ gifts[shareBonusCount].vip4AvgBonus = avgBonus; } //�������ս��� vipTodayBonus[i] = 0; } shareBonusCount++; } //��ȡ�ֺ� function useStatisticalBonusInner() private { User storage user = userRoundMapping[rid][msg.sender]; uint totalAmt = unWithdrawBonus(msg.sender); if(totalAmt > 0){ user.vipBonus = user.vipBonus.add(totalAmt); user.vipTotalBonus = user.vipTotalBonus.add(totalAmt); } //must update checkpoint user.checkpoint = shareBonusCount; } //δ��ȡ�ֺ� function unWithdrawBonus(address _add) public view returns(uint) { User storage user = userRoundMapping[rid][_add]; if(user.id == 0){ return 0; } uint level = user.dynamicLevel; uint checkpoint = user.checkpoint; uint totalAmt = 0; for(uint i = checkpoint;i<shareBonusCount;i++){ if(level == 1){ totalAmt = totalAmt.add(gifts[i].vip1AvgBonus); }else if(level == 2){ totalAmt = totalAmt.add(gifts[i].vip2AvgBonus); }else if(level == 3){ totalAmt = totalAmt.add(gifts[i].vip3AvgBonus); }else if(level == 4){ totalAmt = totalAmt.add(gifts[i].vip4AvgBonus); } } return totalAmt; } //��ȡ�ֺ콱�� function getBonus() public updateReward(msg.sender) checkhalve checkIncreaseCoin { User storage user = userRoundMapping[rid][msg.sender]; require(user.id > 0, "user not exist"); statisticOfDay(); useStatisticalBonusInner(); if(user.vipBonus > 0){ uint dynReward = user.vipBonus; //�ۼ��û���̬�ڿ����� user.hisBtAward = user.hisBtAward.add(dynReward); //��ͨ�� turnover = turnover.add(dynReward); btToken.transfer(msg.sender, dynReward); user.vipBonus = 0; emit RewardPaid(msg.sender, dynReward); } //������ upDynamicLevel(); } modifier checkhalve(){ if(status == 0){ if (block.timestamp >= periodFinish) { changeNotifyRewardAmount(); } } _; } modifier checkStart(){ require(block.timestamp > starttime,"not start"); _; } modifier checkIncreaseCoin(){ increaseCoin(investMoney); _; } function notifyRewardAmount() external onlyWhitelistAdmin updateReward(address(0)) { uint256 reward = 10000 * 1e18; uint256 INIT_DURATION = 10 days; rewardRate = reward.div(INIT_DURATION); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(INIT_DURATION); emit RewardAdded(reward); } function changeNotifyRewardAmount() private { status = 1; uint256 reward = 200000 * 1e18; uint256 DURATION = 400 days; rewardRate = reward.div(DURATION); periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } //ÿ�ղ����� uint public basicCoin = 500 * 1e18; //�������� uint public increaseNumber = 0; //�������� uint increaseUnits = 50 * 1e18; //��������,usdt uint public increaseCondition = 500000 * usdtWei; event LogIncreaseCoin(uint256 _newBasicCoin,uint256 _btBalance,uint _rewardRate,uint256 _periodFinish); //���Ӳ��� function increaseCoin(uint256 total) public { //��ͷ������������������� if(status == 0 || total < increaseCondition){ return; } //������ uint increaseGaps = total.div(increaseCondition); if(increaseGaps > increaseNumber){ //last balance uint balance = btToken.balanceOf(address(this)); if(balance > basicCoin){ uint difference = increaseGaps.sub(increaseNumber); basicCoin = basicCoin.add(difference.mul(increaseUnits)); increaseNumber = increaseGaps; //�������¼������� uint newDuration = balance.div(basicCoin).mul(1 days); rewardRate = balance.div(newDuration); periodFinish = block.timestamp.add(newDuration); emit LogIncreaseCoin(basicCoin,balance,rewardRate,periodFinish); } } } //���Ӻϻ��� function doAddVip(uint _uid,uint _level) private { uint8 flag = 1; if(_level == 1){ vip1s[_uid] = flag; }else if(_level == 2){ vip2s[_uid] = flag; }else if(_level == 3){ vip3s[_uid] = flag; }else if(_level == 4){ vip4s[_uid] = flag; } uint _index = _level - 1; vipLength[_index] = vipLength[_index].add(1); } //�Ƴ��ϻ��� function doRemoveVip(uint _uid,uint _level) private { if(doContainsVip(_uid,_level)){ uint8 flag = 0; if(_level == 1){ vip1s[_uid] = flag; }else if(_level == 2){ vip2s[_uid] = flag; }else if(_level == 3){ vip3s[_uid] = flag; }else if(_level == 4){ vip4s[_uid] = flag; } uint _index = _level - 1; vipLength[_index] = vipLength[_index].sub(1); } } //�����ϻ��� function doContainsVip(uint _uid,uint _level) public view returns (bool) { uint8 flag = 1; if(_level == 1){ return vip1s[_uid] == flag; }else if(_level == 2){ return vip2s[_uid] == flag; }else if(_level == 3){ return vip3s[_uid] == flag; }else if(_level == 4){ return vip4s[_uid] == flag; } return false; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "mul overflow"); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "div zero"); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "lower sub bigger"); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "overflow"); return c; } }
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
7,221,351
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 389, 8443, 273, 389, 3576, 12021, 5621, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 3576, 12021, 1435, 422, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 8863, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 394, 5541, 1769, 203, 3639, 389, 8443, 273, 394, 5541, 31, 203, 565, 289, 203, 97, 2 ]
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/PoolRegistry.sol
10 million represents a sensible upper bound on initial pool, considering that the highest price token per wei is USDC and similar 6-digit stablecoins. So 10 million in that context represents about $10 worth of burned value. Considering that the initial liquidity commitment should be economic de minims, because it's permenately locked, we wouldn't want to be much higher than this.
uint128 constant MAX_INIT_POOL_LIQ = 10_000_000;
4,651,132
[ 1, 2163, 312, 737, 285, 8686, 279, 15390, 1523, 3854, 2489, 603, 2172, 2845, 16, 24453, 716, 326, 9742, 6205, 1147, 1534, 732, 77, 353, 11836, 5528, 471, 7281, 1666, 17, 11052, 14114, 71, 9896, 18, 6155, 1728, 312, 737, 285, 316, 716, 819, 8686, 2973, 271, 2163, 26247, 434, 18305, 329, 460, 18, 23047, 310, 716, 326, 2172, 4501, 372, 24237, 23274, 1410, 506, 425, 591, 24721, 443, 1131, 12097, 16, 2724, 518, 1807, 4641, 275, 5173, 8586, 16, 732, 4102, 82, 1404, 2545, 358, 506, 9816, 10478, 2353, 333, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 10392, 5381, 4552, 67, 12919, 67, 20339, 67, 2053, 53, 273, 1728, 67, 3784, 67, 3784, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// ----------------------------------------------------------------------------- // File RUS_NOUNS_PARADIGMAS.SOL // // (c) Koziev Elijah // SOLARIX Intellectronix Project http://www.solarix.ru // // Лексикон - определения таблиц формообразования (парадигм) для существительных. // // Русские существительные http://www.solarix.ru/for_developers/api/russian-noun-declension.shtml // Особенности описания существительных http://www.solarix.ru/russian_grammar_dictionary/russian-noun-declension.shtml // Словарные статьи http://www.solarix.ru/for_developers/docs/entries.shtml#words // // // 18.12.2009 - для парадигм мужского рода проставлены признаки одушевленности, // чтобы избежать появления (и поправить имеющиеся) ошибок в // винительном падеже. // 19.03.2010 - полная переделка концепции автопарадигм, теперь они не выделяются // особым ключевым словом auto и могут иметь имя для ссылок из // прикладного кода через API. // 02.01.2012 - убраны некоторые малочисленные парадигмы // ----------------------------------------------------------------------------- // // CD->30.12.2000 // LC->01.08.2018 // -------------- #include "sg_defs.h" automat sg { paradigm /*ОПЕРАТОР*/ Сущ_1002 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КАРП ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // КАРПА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // КАРПОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%+А" } // КАРПА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // КАРПУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // КАРПЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+Ы" } :: flexer "pl" // КАРПЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // КАРПОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // КАРПАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // КАРПЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // КАРПАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // КАРПАХ } paradigm Сущ_1003 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ФАЙЛ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ФАЙЛА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ФАЙЛОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ФАЙЛ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ФАЙЛУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ФАЙЛЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+Ы" } :: flexer "pl" // ФАЙЛЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // ФАЙЛОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ФАЙЛАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+Ы" } :: flexer "pl" // ФАЙЛЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ФАЙЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ФАЙЛАХ } paradigm Бахчисарай, Сущ_1005 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Й" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГНОЙ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // ГНОЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ГНОЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ГНОЙ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // ГНОЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГНОЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ГНОИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // ГНОЕВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // ГНОЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ГНОИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // ГНОЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // ГНОЯХ } paradigm /*ДУШ*/ Сущ_1006 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ДУШ ДУШИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // ДУША ДУШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // ДУШЕМ ДУШАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // ДУШ ДУШИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ДУШУ ДУШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ДУШЕ ДУШАХ } paradigm /*СИДОРОВ*/ Сущ_1007 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // ИВАНОВ ИВАНОВЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЫХ" } // ИВАНОВА ИВАНОВЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЫМ" "%+ЫМИ" } // ИВАНОВЫМ ИВАНОВЫМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЫХ" } // ИВАНОВА ИВАНОВЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЫМ" } // ИВАНОВУ ИВАНОВЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЫХ" } // ИВАНОВЕ ИВАНОВЫХ } paradigm ЭТАЖ, Сущ_1068 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЖЧШЩ]" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЭТАЖ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ЭТАЖА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ЭТАЖОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЭТАЖ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ЭТАЖУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ЭТАЖЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // ЭТАЖИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ЕЙ" } :: flexer "pl" // ЭТАЖЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ЭТАЖАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+И" } :: flexer "pl" // ЭТАЖИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ЭТАЖАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ЭТАЖАХ } paradigm /*ЛАРЬ*/ Сущ_1010 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЛАРЬ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // ЛАРЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ЛАРЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЛАРЬ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // ЛАРЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ЛАРЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ЛАРИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Я" } :: flexer "x" // ЛАГЕРЯ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕЙ" } :: flexer "pl" // ЛАРЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // ЛАРЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ЛАРИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // ЛАРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // ЛАРЯХ } paradigm ЦАРЬ, Сущ_1011 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Ь" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ЦАРЬ ЦАРИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // ЦАРЯ ЦАРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЁМ" "%-1%+ЯМИ" } // ЦАРЁМ ЦАРЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // ЦАРЯ ЦАРЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // ЦАРЮ ЦАРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // ЦАРЕ ЦАРЯХ } paradigm КНЯЗЬ, Сущ_1012 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Ь" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Я" } // КНЯЗЬ КНЯЗЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // КНЯЗЯ КНЯЗЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%+ЯМИ" } // КНЯЗЕМ КНЯЗЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // КНЯЗЯ КНЯЗЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%+ЯМ" } // КНЯЗЮ КНЯЗЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+ЯХ" } // КНЯЗЕ КНЯЗЬЯХ } paradigm /*ЛЕС*/ Сущ_1013 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+А" } // ЛЕС ЛЕСА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ЛЕСА ЛЕСОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ЛЕСОМ ЛЕСАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+А" } // ЛЕС ЛЕСА ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ЛЕСУ ЛЕСАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ЛЕСЕ ЛЕСАХ ПАДЕЖ:(МЕСТ) ЧИСЛО:ЕД { "%+У" } // ЛЕСУ } paradigm ГЕРОЙ, Сущ_1015_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Й" { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГЕРОЙ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // ГЕРОЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ГЕРОЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Я" } // ГЕРОЯ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // ГЕРОЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГЕРОЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ГЕРОИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // ГЕРОЕВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // ГЕРОЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // ГЕРОЕВ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // ГЕРОЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // ГЕРОЯХ } paradigm Сергий : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИЙ" { РОД:МУЖ ОДУШ:ОДУШ ПЕРЕЧИСЛИМОСТЬ:НЕТ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // Сергий ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // Сергия ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // Сергием ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Я" } // Сергия ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // Сергию ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // Сергии } paradigm бобслей, Сущ_1015_неодуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Й" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // бобслей ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // бобслея ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // бобслеем ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // бобслей ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // бобслею ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // бобслее ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // бобслеи ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // бобслеев ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // бобслеями ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // бобслеи ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // бобслеям ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // бобслеях } paradigm лепрозорий : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИЙ" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // лепрозорий ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // лепрозория ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // лепрозорием ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // лепрозорий ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // лепрозорию ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // лепрозории ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // лепрозории ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // лепрозориев ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // лепрозориями ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // лепрозории ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // лепрозориям ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // лепрозориях } paradigm МЕДВЕЖОНОК, Сущ_1016 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)НОК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-4%+АТА" } // МЕДВЕЖОНОК МЕДВЕЖАТА ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+КА" "%-4%+АТ" } // МЕДВЕЖОНКА МЕДВЕЖАТ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+КОМ" "%-4%+АТАМИ" } // МЕДВЕЖОНКОМ МЕДВЕЖАТАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+КА" "%-4%+АТ" } // МЕДВЕЖОНКА МЕДВЕЖАТ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+КУ" "%-4%+АТАМ" } // МЕДВЕЖОНКУ МЕДВЕЖАТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+КЕ" "%-4%+АТАХ" } // МЕДВЕЖОНКЕ МЕДВЕЖАТАХ } paradigm ПОРОСЁНОК, Сущ_1017 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЕЁ]НОК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-4%+ЯТА" } // ПОРОСЁНОК ПОРОСЯТА ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+КА" "%-4%+ЯТ" } // ПОРОСЁНКА ПОРОСЯТ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+КОМ" "%-4%+ЯТАМИ" } // ПОРОСЁНКОМ ПОРОСЯТАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+КА" "%-4%+ЯТ" } // ПОРОСЁНКА ПОРОСЯТ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+КУ" "%-4%+ЯТАМ" } // ПОРОСЁНКУ ПОРОСЯТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+КЕ" "%-4%+ЯТАХ" } // ПОРОСЁНКЕ ПОРОСЯТАХ } paradigm ДВОРЯНИН, Сущ_1018 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)НИН" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+Е" } // ДВОРЯНИН ДВОРЯНЕ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2" } // ДВОРЯНИНА ДВОРЯН ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+АМИ" } // ДВОРЯНИНОМ ДВОРЯНАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2" } // ДВОРЯНИНА ДВОРЯН ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+АМ" } // ДВОРЯНИНУ ДВОРЯНАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+АХ" } // ДВОРЯНИНЕ ДВОРЯНАХ } paradigm /*ХОЗЯИН*/ Сущ_1019 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЕВА" } // ХОЗЯИН ХОЗЯЕВА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2%+ЕВ" } // ХОЗЯИНА ХОЗЯЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+ЕВАМИ" } // ХОЗЯИНОМ ХОЗЯЕВАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2%+ЕВ" } // ХОЗЯИНА ХОЗЯЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+ЕВАМ" } // ХОЗЯИНУ ХОЗЯЕВАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+ЕВАХ" } // ХОЗЯИНЕ ХОЗЯЕВАХ } paradigm /*ТАТАРИН*/ Сущ_1020 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+Ы" } // ТАТАРИН ТАТАРЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2" } // ТАТАРИНА ТАТАР ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+АМИ" } // ТАТАРИНОМ ТАТАРАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2" } // ТАТАРИНА ТАТАР ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+АМ" } // ТАТАРИНУ ТАТАРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+АХ" } // ТАТАРИНЕ ТАТАРАХ } paradigm ЦВЕТОК, Сущ_1021 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ОК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+И" } // ЦВЕТОК ЦВЕТКИ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ЦВЕТКА ЦВЕТКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // ЦВЕТКОМ ЦВЕТКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c1%+И" } // ЦВЕТОК ЦВЕТКИ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ЦВЕТКУ ЦВЕТКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ЦВЕТКЕ ЦВЕТКАХ } paradigm /*КОФЕ*/ Сущ_1025 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } // КОФЕ --- } paradigm КЕНГУРУ, Сущ_1026 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)У" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ } paradigm ИЗБРАННИК, Сущ_1027 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ИЗБРАННИК ИЗБРАННИКИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ИЗБРАННИКА ИЗБРАННИКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ИЗБРАННИКОМ ИЗБРАННИКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ОВ" } // ИЗБРАННИКА ИЗБРАННИКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ИЗБРАННИКУ ИЗБРАННИКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ИЗБРАННИКЕ ИЗБРАННИКАХ } paradigm БУЛЬДОГ, Сущ_1042a : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Г" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДОГ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ДОГА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ДОГОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%+А" } // ДОГА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ДОГУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ДОГЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // ДОГИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // ДОГОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ДОГАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // ДОГОВ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ДОГАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ДОГАХ } paradigm ПРОЛОГ, Сущ_1042 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Г" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ПРОЛОГ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ПРОЛОГА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ПРОЛОГОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ПРОЛОГА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ПРОЛОГУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ПРОЛОГЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // ПРОЛОГИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // ПРОЛОГОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ПРОЛОГАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+И" } :: flexer "pl" // ПРОЛОГИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ПРОЛОГАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ПРОЛОГАХ } paradigm БУДЕНЬ, Сущ_1029 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)НЬ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+НИ" } // БУДЕНЬ БУДНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-3%+НЯ" "%-3%+НЕЙ" } // БУДНЯ БУДНЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-3%+НЕМ" "%-3%+НЯМИ" } // БУДНЕМ БУДНЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+НИ" } // БУДЕНЬ БУДНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-3%+НЮ" "%-3%+НЯМ" } // БУДНЮ БУДНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-3%+НЕ" "%-3%+НЯХ" } // БУДНЕ БУДНЯХ } paradigm /*ПАРЕНЬ*/ Сущ_1030 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+НИ" } // ПАРЕНЬ ПАРНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-3%+НЯ" "%-3%+НЕЙ" } // ПАРНЯ ПАРНЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-3%+НЕМ" "%-3%+НЯМИ" } // ПАРНЕМ ПАРНЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-3%+НЯ" "%-3%+НЕЙ" } // ПАРНЯ ПАРНЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-3%+НЮ" "%-3%+НЯМ" } // ПАРНЮ ПАРНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-3%+НЕ" "%-3%+НЯХ" } // ПАРНЕ ПАРНЯХ } paradigm КАМЕШЕК, Сущ_1032_неодуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШ]ЕК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+И" } // КАМЕШЕК КАМЕШКИ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // КАМЕШКА КАМЕШКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // КАМЕШКОМ КАМЕШКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c1%+И" } // КАМЕШЕК КАМЕШКИ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // КАМЕШКУ КАМЕШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // КАМЕШКЕ КАМЕШКАХ } paradigm ПОРОСЁНОЧЕК, Сущ_1032_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШ]ЕК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+И" } // ПОРОСЁНОЧЕК ПОРОСЁНОЧКИ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ПОРОСЁНОЧКА ПОРОСЁНОЧКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // ПОРОСЁНОЧКОМ ПОРОСЁНОЧКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ПОРОСЁНОЧКА ПОРОСЁНОЧКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ПОРОСЁНОЧКУ ПОРОСЁНОЧКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ПОРОСЁНОЧКЕ ПОРОСЁНОЧКАХ } paradigm /*ГОСПОДИН*/ Сущ_1033 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+А" } // ГОСПОДИН ГОСПОДА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2" } // ГОСПОДИНА ГОСПОД ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+АМИ" } // ГОСПОДИНОМ ГОСПОДАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2" } // ГОСПОДИНА ГОСПОД ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+АМ" } // ГОСПОДИНУ ГОСПОДАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+АХ" } // ГОСПОДИНЕ ГОСПОДАХ } paradigm /*МАСТЕР*/ Сущ_1035 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+А" } // МАСТЕР МАСТЕРА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // МАСТЕРА МАСТЕРОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // МАСТЕРОМ МАСТЕРАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ОВ" } // МАСТЕРА МАСТЕРОВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // МАСТЕРУ МАСТЕРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // МАСТЕРЕ МАСТЕРАХ } paradigm /*ГОРОД*/ Сущ_1036 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+А" } // ГОРОД ГОРОДА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ГОРОДА ГОРОДОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ГОРОДОМ ГОРОДАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+А" } // ГОРОД ГОРОДА ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ГОРОДУ ГОРОДАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ГОРОДЕ ГОРОДАХ } paradigm ВРАЧ, Сущ_1037 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Ч" { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ВРАЧ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ВРАЧА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ВРАЧОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%+А" } // ВРАЧА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ВРАЧУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ВРАЧЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // ВРАЧИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ЕЙ" } :: flexer "pl" // ВРАЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ВРАЧАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+ЕЙ" } :: flexer "pl" // ВРАЧЕЙ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ВРАЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ВРАЧАХ } paradigm /*ДРУГ*/ Сущ_1038 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+ЗЬЯ" } // ДРУГ ДРУЗЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-1%+ЗЕЙ" } // ДРУГА ДРУЗЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-1%+ЗЬЯМИ" } // ДРУГОМ ДРУЗЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-1%+ЗЕЙ" } // ДРУГА ДРУЗЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-1%+ЗЬЯМ" } // ДРУГУ ДРУЗЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-1%+ЗЬЯХ" } // ДРУГЕ ДРУЗЬЯХ } paradigm ТОВАРИЩ, Сущ_1039 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШЩ]" { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ТОВАРИЩ ТОВАРИЩИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // ТОВАРИЩА ТОВАРИЩЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // ТОВАРИЩЕМ ТОВАРИЩАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЕЙ" } // ТОВАРИЩА ТОВАРИЩЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ТОВАРИЩУ ТОВАРИЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ТОВАРИЩЕ ТОВАРИЩАХ } paradigm /*РОТ*/ Сущ_1041 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // РОТ РТЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // РТА РТОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // РТОМ РТАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c1%+Ы" } // РОТ РТЫ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // РТУ РТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // РТЕ РТАХ } paradigm /*КОГОТЬ*/ Сущ_1043 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c2%-1%+И" } // КОГОТЬ КОГТИ ПАДЕЖ:(РОД) ЧИСЛО { "%c2%-1%+Я" "%c2%-1%+ЕЙ" } // КОГТЯ КОГТЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%c2%-1%+ЁМ" "%c2%-1%+ЯМИ" } // КОГТЁМ КОГТЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c2%-1%+И" } // КОГОТЬ КОГТИ ПАДЕЖ:ДАТ ЧИСЛО { "%c2%-1%+Ю" "%c2%-1%+ЯМ" } // КОГТЮ КОГТЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c2%-1%+Е" "%c2%-1%+ЯХ" } // КОГТЕ КОГТЯХ } paradigm КОНЬЯК, Сущ_1044 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[КГХШЩ]" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КОНЬЯК ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // КОНЬЯКА ПАДЕЖ:(ПАРТ) ЧИСЛО:ЕД { "%+У" } :: flexer "partitiv" // КОНЬЯКУ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // КОНЬЯКОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // КОНЬЯК ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // КОНЬЯКУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // КОНЬЯКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // КОНЬЯКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // КОНЬЯКОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // КОНЬЯКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+И" } :: flexer "pl" // КОНЬЯКИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // КОНЬЯКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // КОНЬЯКАХ } paradigm /*ПАЛЕЦ*/ Сущ_1045 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬЦЫ" } // ПАЛЕЦ ПАЛЬЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬЦА" "%-2%+ЬЦЕВ" } // ПАЛЬЦА ПАЛЬЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬЦЕМ" "%-2%+ЬЦАМИ" } // ПАЛЬЦЕМ ПАЛЬЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЬЦЫ" } // ПАЛЕЦ ПАЛЬЦЫ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬЦУ" "%-2%+ЬЦАМ" } // ПАЛЬЦУ ПАЛЬЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬЦЕ" "%-2%+ЬЦАХ" } // ПАЛЬЦЕ ПАЛЬЦАХ } paradigm СЛЕДОВАТЕЛЬ, Сущ_1046 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЛЬ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СЛЕДОВАТЕЛЬ СЛЕДОВАТЕЛИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // СЛЕДОВАТЕЛЯ СЛЕДОВАТЕЛЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // СЛЕДОВАТЕЛЕМ СЛЕДОВАТЕЛЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // СЛЕДОВАТЕЛЯ СЛЕДОВАТЕЛЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // СЛЕДОВАТЕЛЮ СЛЕДОВАТЕЛЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // СЛЕДОВАТЕЛЕ СЛЕДОВАТЕЛЯХ } paradigm /*ЧЕЛОВЕЧЕК*/ Сущ_1047 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+И" } // ЧЕЛОВЕЧЕК ЧЕЛОВЕЧКИ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ЧЕЛОВЕЧКА ЧЕЛОВЕЧКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // ЧЕЛОВЕЧКОМ ЧЕЛОВЕЧКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ЧЕЛОВЕЧКА ЧЕЛОВЕЧКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ЧЕЛОВЕЧКУ ЧЕЛОВЕЧКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ЧЕЛОВЕЧКЕ ЧЕЛОВЕЧКАХ } paradigm /*КАФЕТЕРИЙ*/ Сущ_1048 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КАФЕТЕРИЙ КАФЕТЕРИИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕВ" } // КАФЕТЕРИЯ КАФЕТЕРИЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // КАФЕТЕРИЕМ КАФЕТЕРИЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // КАФЕТЕРИЙ КАФЕТЕРИИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // КАФЕТЕРИЮ КАФЕТЕРИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+И" "%-1%+ЯХ" } // КАФЕТЕРИИ КАФЕТЕРИЯХ } paradigm /*ГРОМИЛА*/ Сущ_1049 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГРОМИЛА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // ГРОМИЛЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ГРОМИЛОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ГРОМИЛОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ГРОМИЛУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ГРОМИЛЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГРОМИЛЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // ГРОМИЛЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // ГРОМИЛ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ГРОМИЛАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } :: flexer "pl" // ГРОМИЛ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ГРОМИЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ГРОМИЛАХ } paradigm /*ПАПАША*/ Сущ_1050 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ПАПАША ПАПАШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // ПАПАШИ ПАПАШ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+АМИ" } // ПАПАШЕЙ ПАПАШАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // ПАПАШУ ПАПАШ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ПАПАШЕ ПАПАШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ПАПАШЕ ПАПАШАХ } paradigm /*ЮНОША*/ Сущ_1051 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ЮНОША ЮНОШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+ЕЙ" } // ЮНЮШИ ЮНОШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+АМИ" } // ЮНОШЕЙ ЮНОШАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+ЕЙ" } // ЮНОШУ ЮНОШЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ЮНОШЕ ЮНОШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ЮНОШЕ ЮНОШАХ } paradigm /*ЕГЕРЬ*/ Сущ_1052 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Я" } // ЕГЕРЬ ЕГЕРЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // ЕГЕРЯ ЕГЕРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // ЕГЕРЕМ ЕГЕРЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // ЕГЕРЯ ЕГЕРЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // ЕГЕРЮ ЕГЕРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // ЕГЕРЕ ЕГЕРЯХ } paradigm /*МУРАВЕЙ*/ Сущ_1054 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬИ" } // МУРАВЕЙ МУРАВЬИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬЯ" "%-2%+ЬЁВ" } // МУРАВЬЯ МУРАВЬЁВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬЁМ" "%-2%+ЬЯМИ" } // МУРАВЬЁМ МУРАВЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЬЯ" "%-2%+ЬЁВ" } // МУРАВЬЯ МУРАВЬЁВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬЮ" "%-2%+ЬЯМ" } // МУРАВЬЮ МУРАВЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬЕ" "%-2%+ЬЯХ" } // МУРАВЬЕ МУРАВЬЯХ } paradigm /*КУЛЁК*/ Сущ_1055 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬКИ" } // КУЛЁК КУЛЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // КУЛЬКА КУЛЬКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬКОМ" "%-2%+ЬКАМИ" } // КУЛЬКОМ КУЛЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЬКИ" } // КУЛЁК КУЛЬКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬКУ" "%-2%+ЬКАМ" } // КУЛЬКУ КУЛЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬКЕ" "%-2%+ЬКАХ" } // КУЛЬКЕ КУЛЬКАХ } paradigm /*ПАРЕНЁК*/ Сущ_1056 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬКИ" } // ПАРЕНЁК ПАРЕНЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ПАРЕНЬКА ПАРЕНЬКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬКОМ" "%-2%+ЬКАМИ" } // ПАРЕНЬКОМ ПАРЕНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ПАРЕНЬКА ПАРЕНЬКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬКУ" "%-2%+ЬКАМ" } // ПАРЕНЬКУ ПАРЕНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬКЕ" "%-2%+ЬКАХ" } // ПАРЕНЬКЕ ПАРЕНЬКАХ } paradigm /*ПЛАТЁЖ*/ Сущ_1057 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ПЛАТЁЖ ПЛАТЕЖИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // ПЛАТЕЖА ПЛАТЕЖЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ПЛАТЕЖОМ ПЛАТЕЖАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // ПЛАТЁЖ ПЛАТЕЖИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ПЛАТЕЖУ ПЛАТЕЖАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ПЛАТЕЖЕ ПЛАТЕЖАХ } paradigm /*САРАЙ*/ Сущ_1058 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // САРАЙ САРАИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕВ" } // САРАЯ САРАЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // САРАЕМ САРАЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // САРАЙ САРАИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // САРАЮ САРАЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // САРАЕ САРАЯХ } paradigm /*БУКА*/ Сущ_1059 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // БУКА БУКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // БУКИ БУК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // БУКОЙ БУКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // БУКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // БУКУ БУК ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // БУКЕ БУКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // БУКЕ БУКАХ } paradigm /*ДЕДУШКА*/ Сущ_1060 : СУЩЕСТВИТЕЛЬНОЕ { ОДУШ:ОДУШ РОД:МУЖ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДЕДУШКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ДЕДУШКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ДЕДУШКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДЕДУШКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ДЕДУШКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ДЕДУШКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ДЕДУШКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ДЕДУШКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-2%+ЕК" } :: flexer "pl" // ДЕДУШЕК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ДЕДУШКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-2%+ЕК" } :: flexer "pl" // ДЕДУШЕК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ДЕДУШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ДЕДУШКАХ } paradigm ДЯДЕНЬКА, Сущ_1061 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЬКА" { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДЯДЕНЬКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ДЯДЕНЬКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ДЯДЕНЬКОЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ДЯДЕНЬКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ДЯДЕНЬКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ДЯДЕНЬКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ДЯДЕНЬКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-3%+ЕК" } :: flexer "pl" // ДЯДЕНЕК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ДЯДЕНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-3%+ЕК" } :: flexer "pl" // ДЯДЕНЕК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ДЯДЕНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ДЯДЕНЬКАХ } paradigm /*ОРЁЛ*/ Сущ_1062 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // ОРЁЛ ОРЛЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ОРЛА ОРЛОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // ОРЛОМ ОРЛАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ОРЛА ОРЛОВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ОРЛУ ОРЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ОРЛЕ ОРЛАХ } paradigm /*ПЛАЩ*/ Сущ_1064 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ПЛАЩ ПЛАЩИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // ПЛАЩА ПЛАЩЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЁМ" "%+АМИ" } // ПЛАЩЁМ ПЛАЩАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // ПЛАЩ ПЛАЩИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ПЛАЩУ ПЛАЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ПЛАЩЕ ПЛАЩАХ } paradigm /*МЕСЯЦ*/ Сущ_1065 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // МЕСЯЦ МЕСЯЦЫ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+А" } // --- МЕСЯЦА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕВ" } // МЕСЯЦА МЕСЯЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // МЕСЯЦЕМ МЕСЯЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+Ы" } // МЕСЯЦ МЕСЯЦЫ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+А" } // --- МЕСЯЦА ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // МЕСЯЦУ МЕСЯЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // МЕСЯЦЕ МЕСЯЦАХ } paradigm КРИК, Сущ_1067 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@аК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // КРИК КРИКИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // КРИКА КРИКОВ ПАДЕЖ:(ПАРТ) ЧИСЛО:ЕД { "%+У" } // КРИКУ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // КРИКОМ КРИКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // КРИК КРИКИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // КРИКУ КРИКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // КРИКЕ КРИКАХ } paradigm /*ШОФЁР*/ Сущ_1069 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЕРА" } // ШОФЁР ШОФЕРА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2%+ЕРОВ" } // ШОФЁРА ШОФЕРОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+ЕРАМИ" } // ШОФЁРОМ ШОФЕРАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2%+ЕРОВ" } // ШОФЁРА ШОФЕРОВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+ЕРАМ" } // ШОФЁРУ ШОФЕРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+ЕРАХ" } // ШОФЁРЕ ШОФЕРАХ } paradigm /*ВЕРХ*/ Сущ_1070 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ВЕРХ ВЕРХИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ВЕРХА ВЕРХОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ВЕРХОМ ВЕРХАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // ВЕРХ ВЕРХИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ВЕРХУ ВЕРХАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ВЕРХЕ ВЕРХАХ } paradigm /*УЖАС*/ Сущ_1071 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // УЖАС УЖАСЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // УЖАСА УЖАСОВ ПАДЕЖ:(ПАРТ) ЧИСЛО:ЕД { "%+У" } // УЖАСУ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // УЖАСОМ УЖАСАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+Ы" } // УЖАС УЖАСЫ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // УЖАСУ УЖАСАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // УЖАСЕ УЖАСАХ } paradigm /*СТРАЖ*/ Сущ_1072_одуш : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // СТРАЖ СТРАЖИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // СТРАЖА СТРАЖЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // СТРАЖЕМ СТРАЖАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЕЙ" } // СТРАЖА СТРАЖЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // СТРАЖУ СТРАЖАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // СТРАЖЕ СТРАЖАХ } paradigm /*КУКИШ*/ Сущ_1072_неодуш : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // КУКИШ КУКИШИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // КУКИША КУКИШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // КУКИШЕМ КУКИШАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // КУКИШ КУКИШИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // КУКИШУ КУКИШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // КУКИШЕ КУКИШАХ } paradigm /*РОСТ*/ Сущ_1073 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // РОСТ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // РОСТА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // РОСТОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // РОСТ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // РОСТУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // РОСТЕ } paradigm /*БРАТ*/ Сущ_1076 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+ЬЯ" } // БРАТ БРАТЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЬЕВ" } // БРАТА БРАТЬЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+ЬЯМИ" } // БРАТОМ БРАТЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЬЕВ" } // БРАТА БРАТЬЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЬЯМ" } // БРАТУ БРАТЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЬЯХ" } // БРАТЕ БРАТЬЯХ } paradigm ПРИШЕЛЕЦ, Сущ_1078 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЦ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬЦЫ" } // ПРИШЕЛЕЦ ПРИШЕЛЬЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬЦА" "%-2%+ЬЦЕВ" } // ПРИШЕЛЬЦА ПРИШЕЛЬЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬЦЕМ" "%-2%+ЬЦАМИ" } // ПРИШЕЛЬЦЕМ ПРИШЕЛЬЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЬЦА" "%-2%+ЬЦЕВ" } // ПРИШЕЛЬЦА ПРИШЕЛЬЦЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬЦУ" "%-2%+ЬЦАМ" } // ПРИШЕЛЬЦУ ПРИШЕЛЬЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬЦЕ" "%-2%+ЬЦАХ" } // ПРИШЕЛЬЦЕ ПРИШЕЛЬЦАХ } paradigm /*СТУЛ*/ Сущ_1079 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+ЬЯ" } // СТУЛ СТУЛЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЬЕВ" } // СТУЛА СТУЛЬЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+ЬЯМИ" } // СТУЛОМ СТУЛЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+ЬЯ" } // СТУЛ СТУЛЬЯ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЬЯМ" } // СТУЛУ СТУЛЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЬЯХ" } // СТУЛЕ СТУЛЬЯХ } paradigm /*СОСЕД*/ Сущ_1080 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // СОСЕД СОСЕДИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // СОСЕДА СОСЕДЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+ЯМИ" } // СОСЕДОМ СОСЕДЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЕЙ" } // СОСЕДА СОСЕДЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЯМ" } // СОСЕДУ СОСЕДЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЯХ" } // СОСЕДЕ СОСЕДЯХ } paradigm ДИМКА, Сущ_1081 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бКА" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ЧИСЛО:ЕД |{ ПАДЕЖ:(ИМ) { "" } // ДИМКА ПАДЕЖ:(РОД) { "%-1%+И" } // ДИМКИ ПАДЕЖ:ТВОР { "%-1%+ОЙ" } // ДИМКОЙ ПАДЕЖ:ВИН { "%-1%+У" } // ДИМКУ ПАДЕЖ:ДАТ { "%-1%+Е" } // ДИМКЕ ПАДЕЖ:(ПРЕДЛ) { "%-1%+Е" } // ДИМКЕ } } paradigm /*УЧЁНЫЙ*/ Сущ_1083 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Е" } // УЧЁНЫЙ УЧЁНЫЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ОГО" "%-1%+Х" } // УЧЁНОГО УЧЁНЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+М" "%-1%+МИ" } // УЧЁНЫМ УЧЁНЫМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ОГО" "%-1%+Х" } // УЧЁНОГО УЧЁНЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ОМУ" "%-1%+М" } // УЧЁНОМУ УЧЁНЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ОМ" "%-1%+Х" } // УЧЁНОМ УЧЁНЫХ } paradigm /*МАЛЫШ*/ Сущ_1084 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // МАЛЫШ МАЛЫШИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // МАЛЫША МАЛЫШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // МАЛЫШОМ МАЛЫШАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЕЙ" } // МАЛЫША МАЛЫШЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // МАЛЫШУ МАЛЫШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // МАЛЫШЕ МАЛЫШАХ } paradigm /*СЛУГА*/ Сущ_1086 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СЛУГА СЛУГИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // СЛУГИ СЛУГ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // СЛУГОЙ СЛУГАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // СЛУГУ СЛУГ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // СЛУГЕ СЛУГАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // СЛУГЕ СЛУГАХ } paradigm ОГОНЁК, Сущ_1087_неодуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЕК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬКИ" } // ОГОНЁК ОГОНЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ОГОНЬКА ОГОНЬКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬКОМ" "%-2%+ЬКАМИ" } // ОГОНЬКОМ ОГОНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЬКИ" } // ОГОНЁК ОГОНЬКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬКУ" "%-2%+ЬКАМ" } // ОГОНЬКУ ОГОНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬКЕ" "%-2%+ЬКАХ" } // ОГОНЬКЕ ОГОНЬКАХ } paradigm ИГОРЁК, Сущ_1087_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЕК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬКИ" } // ИГОРЁК ИГОРЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ИГОРЬКА ИГОРЬКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬКОМ" "%-2%+ЬКАМИ" } // ИГОРЬКОМ ИГОРЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ИГОРЬКА ИГОРЬКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬКУ" "%-2%+ЬКАМ" } // ИГОРЬКУ ИГОРЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬКЕ" "%-2%+ЬКАХ" } // ИГОРЬКЕ ИГОРЬКАХ } paradigm УБИЙЦА, Сущ_1088 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЙЦА" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // УБИЙЦА УБИЙЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Ы" "%-1" } // УБИЙЦЫ УБИЙЦ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+АМИ" } // УБИЙЦЕЙ УБИЙЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // УБИЙЦУ УБИЙЦ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // УБИЙЦЕ УБИЙЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // УБИЙЦЕ УБИЙЦАХ } paradigm ДОМИШКА, Сущ_1091 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШЩ]КА" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДОМИШКА ДОМИШКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕК" } // ДОМИШКИ ДОМИШЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // ДОМИШКОЙ ДОМИШКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // ДОМИШКА ДОМИШКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ДОМИШКЕ ДОМИШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ДОМИШКЕ ДОМИШКАХ } paradigm ОЛИМПИЕЦ, Сущ_1092 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИЕЦ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЙЦЫ" } // ОЛИМПИЕЦ ОЛИМПИЙЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЙЦА" "%-2%+ЙЦЕВ" } // ОЛИМПИЙЦА ОЛИМПИЙЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЙЦЕМ" "%-2%+ЙЦАМИ" } // ОЛИМПИЙЦЕМ ОЛИМПИЙЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЙЦА" "%-2%+ЙЦЕВ" } // ОЛИМПИЙЦА ОЛИМПИЙЦЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЙЦУ" "%-2%+ЙЦАМ" } // ОЛИМПИЙЦУ ОЛИМПИЙЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЙЦЕ" "%-2%+ЙЦАХ" } // ОЛИМПИЙЦЕ ОЛИМПИЙЦАХ } paradigm /*ТАНЕЦ*/ Сущ_1093 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // ТАНЕЦ ТАНЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ЕВ" } // ТАНЦА ТАНЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ЕМ" "%c1%+АМИ" } // ТАНЦЕМ ТАНЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c1%+Ы" } // ТАНЕЦ ТАНЦЫ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ТАНЦУ ТАНЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ТАНЦЕ ТАНЦАХ } paradigm МЕРЗАВЕЦ, Сущ_1094 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЦ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // МЕРЗАВЕЦ МЕРЗАВЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ЕВ" } // МЕРЗАВЦА МЕРЗАВЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ЕМ" "%c1%+АМИ" } // МЕРЗАВЦЕМ МЕРЗАВЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ЕВ" } // МЕРЗАВЦА МЕРЗАВЦЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // МЕРЗАВЦУ МЕРЗАВЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // МЕРЗАВЦЕ МЕРЗАВЦАХ } paradigm ДВОРЕЦ, Сущ_1095 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЦ" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДВОРЕЦ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%c1%+А" } // ДВОРЦА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%c1%+ОМ" } // ДВОРЦОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ДВОРЕЦ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%c1%+У" } // ДВОРЦУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%c1%+Е" } // ДВОРЦЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%c1%+Ы" } :: flexer "pl" // ДВОРЦЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%c1%+ОВ" } :: flexer "pl" // ДВОРЦОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%c1%+АМИ" } :: flexer "pl" // ДВОРЦАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%c1%+Ы" } :: flexer "pl" // ДВОРЦЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%c1%+АМ" } :: flexer "pl" // ДВОРЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%c1%+АХ" } :: flexer "pl" // ДВОРЦАХ } paradigm САМЕЦ, Сущ_1096 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЦ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // САМЕЦ САМЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // САМЦА САМЦОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // САМЦОМ САМЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // САМЦА САМЦОВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // САМЦУ САМЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // САМЦЕ САМЦАХ } paradigm /*КОМАНДУЮЩИЙ*/ Сущ_1097 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Е" } // КОМАНДУЮЩИЙ КОМАНДУЮЩИЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЕГО" "%-1%+Х" } // КОМАНДУЮЩЕГО КОМАНДУЮЩИХ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+М" "%-1%+МИ" } // КОМАНДУЮЩИМ КОМАНДУЮЩИМ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЕГО" "%-1%+Х" } // КОМАНДУЮЩЕГО КОМАНДУЮЩИХ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЕМУ" "%-1%+М" } // КОМАНДУЮЩЕМУ КОМАНДУЮЩИМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЕМ" "%-1%+Х" } // КОМАНДУЮЩЕМ КОМАНДУЮЩИХ } paradigm ДОСТОЕВСКИЙ, Сущ_1098 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)СКИЙ" { ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ РОД:МУЖ ЧИСЛО:ЕД |{ ПАДЕЖ:(ИМ) { "" } // Достоевский ПАДЕЖ:(РОД) { "%-2%+ОГО" } // Достоевского ПАДЕЖ:ТВОР { "%-2%+ИМ" } // достоевским ПАДЕЖ:ВИН { "%-2%+ОГО" } // Достоевского ПАДЕЖ:ДАТ { "%-2%+ОМУ" } // Достоевскому ПАДЕЖ:(ПРЕДЛ) { "%-2%+ОМ" } // Достоевском } } paradigm ДЫМИЩЕ, Сущ_1099 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЩЕ" { РОД:МУЖ ОДУШ:НЕОДУШ ПЕРЕЧИСЛИМОСТЬ:ДА ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДЫМИЩЕ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ДЫМИЩА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ДЫМИЩЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ДЫМИЩЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ДЫМИЩУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ДЫМИЩЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } // ДЫМИЩИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } // ДЫМИЩ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // ДЫМИЩАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+А" } // ДЫМИЩА ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // ДЫМИЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // ДЫМИЩАХ } paradigm ОКУНИЩЕ, Сущ_1100 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЩЕ" { РОД:МУЖ ОДУШ:ОДУШ ПЕРЕЧИСЛИМОСТЬ:ДА ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ОКУНИЩЕ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ОКУНИЩА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ОКУНИЩЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+А" } // ОКУНИЩА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ОКУНИЩУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ОКУНИЩЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } // ОКУНИЩИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+А" } // ОКУНИЩА ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // ОКУНИЩ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } // ОКУНИЩ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // ОКУНИЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // ОКУНИЩАХ } // ======================================================================= paradigm /*МАТЬ*/ Сущ_2001 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+ЕРИ" } // МАТЬ МАТЕРИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+ЕРИ" "%-1%+ЕРЕЙ" } // МАТЕРИ МАТЕРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕРЬЮ" "%-1%+ЕРЯМИ" } // МАТЕРЬЮ МАТЕРЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+ЕРЕЙ" } // МАТЬ МАТЕРЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+ЕРИ" "%-1%+ЕРЯМ" } // МАТЕРИ МАТЕРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+ЕРИ" "%-1%+ЕРЯХ" } // МАТЕРИ МАТЕРЯХ } paradigm /*ТЬМА*/ Сущ_2002 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // ТЬМА ТЬМЫ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // ТЬМЫ - ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // ТЬМОЙ ТЬМАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ТЬМОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+Ы" } // ТЬМУ ТЬМЫ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ТЬМЕ ТЬМАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ТЬМЕ ТЬМАХ } paradigm БЛОНДИНКА, Сущ_2003 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бКА" { РОД:ЖЕН ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // БЛОНДИНКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // БЛОНДИНКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // БЛОНДИНКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // БЛОНДИНКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // БЛОНДИНКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // БЛОНДИНКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // БЛОНДИНКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // БЛОНДИНКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-2%+ОК" } :: flexer "pl" // БЛОНДИНОК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // БЛОНДИНКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-2%+ОК" } :: flexer "pl" // БЛОНДИНОК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // БЛОНДИНКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // БЛОНДИНКАХ } paradigm /*ВОШЬ*/ Сущ_2004 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ШИ" } // ВОШЬ ВШИ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "%-3%+ША" } // ВША ПАДЕЖ:(РОД) ЧИСЛО { "%-3%+ШИ" "%-3%+ШЕЙ" } // ВШИ ВШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+Ю" "%-3%+ШАМИ" } // ВОШЬЮ ВШАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-3%+ШОЙ" } // ВШОЙ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+ШЕЙ" } // ВОШЬ ВШЕЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-3%+ШУ" } // ВШУ ПАДЕЖ:ДАТ ЧИСЛО { "%-3%+ШЕ" "%-3%+ШАМ" } // ВШЕ ВШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-3%+ШЕ" "%-3%+ШАХ" } // ВШЕ ВШАХ } paradigm МАМА, Сущ_2006 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)А" { РОД:ЖЕН ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // МАМА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // МАМЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // МАМОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // МАМОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // МАМУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // МАМЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // МАМЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // МАМЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // МАМ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // МАМАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } :: flexer "pl" // МАМ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // МАМАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // МАМАХ } paradigm ЦВЕТАЕВА, Сущ_2006_Фамилия : СУЩЕСТВИТЕЛЬНОЕ for "(.+)А" { РОД:ЖЕН ОДУШ:ОДУШ ПЕРЕЧИСЛИМОСТЬ:НЕТ CharCasing:FirstCapitalized ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЦВЕТАЕВА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+ОЙ" } // ЦВЕТАЕВОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ЦВЕТАЕВОЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ЦВЕТАЕВУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+ОЙ" } // ЦВЕТАЕВОЙ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+ОЙ" } // ЦВЕТАЕВОЙ } paradigm РОЗА, Сущ_2007 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)А" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // РОЗА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // РОЗЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // РОЗОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // РОЗОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // РОЗУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // РОЗЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // РОЗЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // РОЗЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // РОЗ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // РОЗАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // РОЗЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // РОЗАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // РОЗАХ } paradigm СУХОСТЬ, Сущ_2008 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ОСТЬ" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // СУХОСТЬ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // СУХОСТИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+Ю" } // СУХОСТЬЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // СУХОСТЬ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+И" } // СУХОСТИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // СУХОСТИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // СУХОСТИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕЙ" } :: flexer "pl" // СУХОСТЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // СУХОСТЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // СУХОСТИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // СУХОСТЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // СУХОСТЯХ } paradigm ХАРЯ, Сущ_2009 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЯ" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ХАРЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ХАРИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ХАРЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ХАРЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ХАРЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ХАРЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ХАРЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ХАРИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+Ь" } :: flexer "pl" // ХАРЬ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // ХАРЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ХАРИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // ХАРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // ХАРЯХ } paradigm ГУСЫНЯ, Сущ_2009_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЯ" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГУСЫНЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ГУСЫНИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ГУСЫНЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ГУСЫНЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ГУСЫНЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ГУСЫНЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГУСЫНЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } // ГУСЫНИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+Ь" } // ГУСЫНЬ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } // ГУСЫНЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+Ь" } // ГУСЫНЬ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } // ГУСЫНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } // ГУСЫНЯХ } paradigm ОЛЯ, Сущ_2009_имя : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Я" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ CharCasing:FirstCapitalized ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // Оля ПАДЕЖ:ЗВАТ ЧИСЛО:ЕД { "%-1%+Ь" } :: flexer "vocative" // Оль ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // Оли ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // Олей ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // Олю ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // Оле ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // Оле } paradigm ЭМИССИЯ, Сущ_2010 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ИЬ]Я" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЭМИССИЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ЭМИССИИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ЭМИССИЕЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ЭМИССИЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+И" } // ЭМИССИИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // ЭМИССИИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ЭМИССИИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+Й" } :: flexer "pl" // ЭМИССИЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // ЭМИССИЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ЭМИССИИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // ЭМИССИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // ЭМИССИЯХ } // с дополнительной формой творительного падежа paradigm ИСТОРИЯ, Сущ_2010_2 : СУЩЕСТВИТЕЛЬНОЕ { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ИСТОРИЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ИСТОРИИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ИСТОРИЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ИСТОРИЕЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ИСТОРИЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+И" } // ИСТОРИИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // ИСТОРИИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ИСТОРИИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+Й" } :: flexer "pl" // ИСТОРИЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // ИСТОРИЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ИСТОРИИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // ИСТОРИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // ИСТОРИЯХ } paradigm /*МЫШЬ*/ Сущ_2011_одуш : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // МЫШЬ МЫШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+ЕЙ" } // МЫШИ МЫШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+Ю" "%-1%+АМИ" } // МЫШЬЮ МЫШАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+ЕЙ" } // МЫШЬ МЫШЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+И" "%-1%+АМ" } // МЫШИ МЫШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+И" "%-1%+АХ" } // МЫШИ МЫШАХ } paradigm /*НОЧЬ*/ Сущ_2011_неодуш : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // НОЧЬ НОЧИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+ЕЙ" } // НОЧИ НОЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+Ю" "%-1%+АМИ" } // НОЧЬЮ НОЧАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // НОЧЬ НОЧЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+И" "%-1%+АМ" } // НОЧИ НОЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+И" "%-1%+АХ" } // НОЧИ НОЧАХ } paradigm ДЕВУШКА, Сущ_2013 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШЩ]КА" { РОД:ЖЕН ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДЕВУШКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ДЕВУШКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ДЕВУШКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДЕВУШКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ДЕВУШКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ДЕВУШКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ДЕВУШКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ДЕВУШКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-2%+ЕК" } :: flexer "pl" // ДЕВУШЕК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ДЕВУШКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-2%+ЕК" } :: flexer "pl" // ДЕВУШЕК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ДЕВУШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ДЕВУШКАХ } paradigm ДВУШКА, Сущ_2014 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бКА" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДВУШКА ДВУШКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕК" } // ДВУШКИ ДВУШЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // ДВУШКОЙ ДВУШКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДВУШКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // ДВУШКУ ДВУШКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ДВУШКЕ ДВУШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ДВУШКЕ ДВУШКАХ } paradigm РУКА, Сущ_2015 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[КХ]А" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // РУКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // РУКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // РУКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // РУКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // РУКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // РУКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // РУКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // РУКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // РУК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // РУКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // РУКИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // РУКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // РУКАХ } paradigm СНОХА, Сущ_2015a : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[КХ]А" { РОД:ЖЕН ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // СНОХА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // СНОХИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // СНОХОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СНОХОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // СНОХУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // СНОХЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // СНОХЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // СНОХИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // СНОХ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // СНОХАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } :: flexer "pl" // СНОХ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // СНОХАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // СНОХАХ } paradigm /*ДЕНЬГА*/ Сущ_2016 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДЕНЬГА ДЕНЬГИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕГ" } // ДЕНЬГИ ДЕНЕГ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%+МИ" } // ДЕНЬГОЙ ДЕНЬГАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДЕНЬГОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // ДЕНЬГУ ДЕНЬГИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ДЕНЬГЕ ДЕНЬГАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ДЕНЬГЕ ДЕНЬГАХ } paradigm /*ЖЕНА*/ Сущ_2017 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁНЫ" } // ЖЕНА ЖЁНЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Ы" "%-3%+ЁН" } // ЖЕНЫ ЖЁН ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-3%+ЁНАМИ" } // ЖЕНОЙ ЖЁНАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ЖЕНОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-3%+ЁН" } // ЖЕНУ ЖЁН ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-3%+ЁНАМ" } // ЖЕНЕ ЖЁНАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁНАХ" } // ЖЕНЕ ЖЁНАХ } paradigm УЛИЦА, Сущ_2018 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЦА" { ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // УЛИЦА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // УЛИЦЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // УЛИЦЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // УЛИЦЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // УЛИЦУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // УЛИЦЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // УЛИЦЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // УЛИЦЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // УЛИЦ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // УЛИЦАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // УЛИЦЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // УЛИЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // УЛИЦАХ } paradigm /*ПТИЦА*/ Сущ_2018a : СУЩЕСТВИТЕЛЬНОЕ { ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // ПТИЦА ПТИЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Ы" "%-1" } // ПТИЦЫ ПТИЦ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // ПТИЦЕЙ ПТИЦАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ПТИЦЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // ПТИЦУ ПТИЦ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ПТИЦЕ ПТИЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ПТИЦЕ ПТИЦАХ } paradigm /*НАТАША*/ Сущ_2018_2a : СУЩЕСТВИТЕЛЬНОЕ { ОДУШ:ОДУШ РОД:ЖЕН ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // НАТАША ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // НАТАШИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // НАТАШЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // НАТАШЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // НАТАШУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // НАТАШЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // НАТАШЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // БАНКИРШИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // БАНКИРШ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // БАНКИРШАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } :: flexer "pl" // БАНКИРШ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // БАНКИРШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // БАНКИРШАХ } paradigm /*КУХНЯ*/ Сущ_2019 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КУХНЯ КУХНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ОНЬ" } // КУХНИ КУХОНЬ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+ЯМИ" } // КУХНЕЙ КУХНЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // КУХНЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // КУХНЮ КУХНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // КУХНЕ КУХНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // КУХНЕ КУХНЯХ } paradigm ТРУБКА, Сущ_2020 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бКА" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ТРУБКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ТРУБКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ТРУБКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ТРУБКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ТРУБКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ТРУБКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ТРУБКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ТРУБКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-2%+ОК" } :: flexer "pl" // ТРУБОК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // ТРУБКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ТРУБКИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ТРУБКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ТРУБКАХ } paradigm /*ПРИРОДА*/ Сущ_2021 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ПРИРОДА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // ПРИРОДЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ"} // ПРИРОДОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ"} // ПРИРОДОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ПРИРОДУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ПРИРОДЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ПРИРОДЕ } paradigm /*ЧУШЬ*/ Сущ_2022 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЧУШЬ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ЧУШИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+Ю" } // ЧУШЬЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЧУШЬ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+И" } // ЧУШИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // ЧУШИ } paradigm /*ВАННАЯ*/ Сущ_2023 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЫЕ" } // ВАННАЯ ВАННЫЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ОЙ" "%-2%+ЫХ" } // ВАННОЙ ВАННЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ОЙ" "%-2%+ЫМИ" } // ВАННОЙ ВАННЫМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-2%+ОЮ" } // ВАННОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+УЮ" "%-2%+ЫЕ" } // ВАННУЮ ВАННЫЕ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ОЙ" "%-2%+ЫМ" } // ВАННОЙ ВАННЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ОЙ" "%-2%+ЫХ" } // ВАННОЙ ВАННЫХ } paradigm /*ПРИХОЖАЯ*/ Сущ_2024 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ИЕ" } // ПРИХОЖАЯ ПРИХОЖИЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЕЙ" "%-2%+ИХ" } // ПРИХОЖЕЙ ПРИХОЖИХ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЕЙ" "%-2%+ИМИ" } // ПРИХОЖЕЙ ПРИХОЖИМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-2%+ЕЮ" } // ПРИХОЖЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+УЮ" "%-2%+ИЕ" } // ПРИХОЖУЮ ПРИХОЖИЕ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЕЙ" "%-2%+ИМ" } // ПРИХОЖЕЙ ПРИХОЖИМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЕЙ" "%-2%+ИХ" } // ПРИХОЖЕЙ ПРИХОЖЫХ } paradigm НЯНЬКА, Сущ_2025 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЬКА" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // НЯНЬКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // НЯНЬКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // НЯНЬКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // НЯНЬКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // НЯНЬКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // НЯНЬКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // НЯНЬКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // НЯНЬКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-3%+ЕК" } :: flexer "pl" // НЯНЕК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // НЯНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-3%+ЕК" } :: flexer "pl" // НЯНЕК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // НЯНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // НЯНЬКАХ } paradigm /*ЛЕДИ*/ Сущ_2026 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ } paradigm /*ЗЕМЛЯ*/ Сущ_2027 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ЗЕМЛЯ ЗЕМЛИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕЛЬ" } // ЗЕМЛИ ЗЕМЕЛЬ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЁЙ" "%-1%+ЯМИ" } // ЗЕМЛЁЙ ЗЕМЛЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЁЮ" } // ЗЕМЛЁЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ЗЕМЛЮ ЗЕМЛИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // ЗЕМЛЕ ЗЕМЛЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // ЗЕМЛЕ ЗЕМЛЯХ } paradigm /*ШЕЯ*/ Сущ_2028 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ШЕЯ ШЕИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+Й" } // ШЕИ ШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // ШЕЕЙ ШЕЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ШЕЮ ШЕИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ШЕЕ ШЕЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ШЕЕ ШЕЯХ } paradigm ТЫСЯЧА, Сущ_2030 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШЩ]А" { ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ТЫСЯЧА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ТЫСЯЧИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ТЫСЯЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ТЫСЯЧЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ТЫСЯЧУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ТЫСЯЧЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ТЫСЯЧЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ТЫСЯЧИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // ТЫСЯЧ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ТЫСЯЧАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ТЫСЯЧИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ТЫСЯЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ТЫСЯЧАХ } paradigm /*СОБАКА*/ Сущ_2031 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СОБАКА СОБАКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // СОБАКИ СОБАК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%+МИ" } // СОБАКОЙ СОБАКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СОБАКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // СОБАКУ СОБАК ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // СОБАКЕ СОБАКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // СОБАКЕ СОБАКАХ } paradigm /*СПАЛЬНЯ*/ Сущ_2032 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СПАЛЬНЯ СПАЛЬНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕН" } // СПАЛЬНИ СПАЛЕН ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+ЯМИ" } // СПАЛЬНЕЙ СПАЛЬНЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // СПАЛЬНЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // СПАЛЬНЮ СПАЛЬНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // СПАЛЬНЕ СПАЛЬНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // СПАЛЬНЕ СПАЛЬНЯХ } paradigm СКАМЕЙКА, Сущ_2035 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЙКА" { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СКАМЕЙКА СКАМЕЙКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕК" } // СКАМЕЙКИ СКАМЕЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // СКАМЕЙКОЙ СКАМЕЙКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СКАМЕЙКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // СКАМЕЙКУ СКАМЕЙКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // СКАМЕЙКЕ СКАМЕЙКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // СКАМЕЙКЕ СКАМЕЙКАХ } paradigm КАНАРЕЙКА, Сущ_2035_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЙКА" { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КАНАРЕЙКА КАНАРЕЙКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕК" } // КАНАРЕЙКИ КАНАРЕЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // КАНАРЕЙКОЙ КАНАРЕЙКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // КАНАРЕЙКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-3%+ЕК" } // КАНАРЕЙКУ КАНАРЕЕК ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // КАНАРЕЙКЕ КАНАРЕЙКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // КАНАРЕЙКЕ КАНАРЕЙКАХ } paradigm /*ЩЕКА*/ Сущ_2036 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁКИ" } // ЩЕКА ЩЁКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЁК" } // ЩЕКИ ЩЁК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-3%+ЁКАМИ" } // ЩЕКОЙ ЩЁКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ЩЕКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-3%+ЁКИ" } // ЩЕКУ ЩЁКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-3%+ЁКАМ" } // ЩЕКЕ ЩЁКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁКАХ" } // ЩЕКЕ ЩЁКАХ } paradigm /*СУДЬБА*/ Сущ_2037 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // СУДЬБА СУДЬБЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Ы" "%-3%+ЕБ" } // СУДЬБЫ СУДЕБ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%+МИ" } // СУДЬБОЙ СУДЬБАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СУДЬБОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+Ы" } // СУДЬБУ СУДЬБЫ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // СУДЬБЕ СУДЬБАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // СУДЬБЕ СУДЬБАХ } paradigm СВЕЧА, Сущ_2038 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЧА" { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СВЕЧ СВЕЧИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+ЕЙ" } // СВЕЧИ СВЕЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // СВЕЧОЙ СВЕЧАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СВЕЧОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // СВЕЧУ СВЕЧИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // СВЕЧЕ СВЕЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // СВЕЧЕ СВЕЧАХ } paradigm /*ЧЕПУХА*/ Сущ_2039 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЧЕПУХА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ЧЕПУХИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ"} // ЧЕПУХОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ"} // ЧЕПУХОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ЧЕПУХУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ЧЕПУХЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ЧЕПУХЕ } paradigm /*ВОЛЯ*/ Сущ_2040 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ВОЛЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ВОЛИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ"} // ВОЛЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ"} // ВОЛЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ВОЛЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ВОЛЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ВОЛЕ } paradigm /*ЗМЕЯ*/ Сущ_2041 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ЗМЕЯ ЗМЕИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+Й" } // ЗМЕИ ЗМЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЁЙ" "%+МИ" } // ЗМЕЁЙ ЗМЕЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЁЮ" } // ЗМЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ЗМЕЮ ЗМЕИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ЗМЕЕ ЗМЕЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ЗМЕЕ ЗМЕЯХ } // несклоняемые paradigm /*СОЛЯРИС*/ Сущ_2042 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:ВИН ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } :: flexer "pl" } paradigm /*КАПЛЯ*/ Сущ_2044 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КАПЛЯ КАПЛИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕЛЬ" } // КАПЛИ КАПЕЛЬ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+ЯМИ" } // КАПЛЕЙ КАПЛЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // КАПЛЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // КАПЛЮ КАПЛИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // КАПЛЕ КАПЛЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // КАПЛЕ КАПЛЯХ } paradigm /*ДЕРЕВНЯ*/ Сущ_2045 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДЕРЕВНЯ ДЕРЕВНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕНЬ" } // ДЕРЕВНИ ДЕРЕВЕНЬ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+ЯМИ" } // ДЕРЕВНЕЙ ДЕРЕВНЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ДЕРЕВНЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ДЕРЕВНЮ ДЕРЕВНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // ДЕРЕВНЕ ДЕРЕВНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // ДЕРЕВНЕ ДЕРЕВНЯХ } paradigm /*ДУША*/ Сущ_2048 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДУША ДУШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // ДУШИ ДУШ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // ДУШОЙ ДУШАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДУШОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // ДУШУ ДУШИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ДУШЕ ДУШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ДУШЕ ДУШАХ } paradigm /*ПИЩА*/ Сущ_2049 : СУЩЕСТВИТЕЛЬНОЕ { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ПИЩА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ПИЩИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ПИЩЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ПИЩЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ПИЩУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ПИЩЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ПИЩЕ } paradigm СТУПЕНЬКА, Сущ_2050 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЬКА" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СТУПЕНЬКА СТУПЕНЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕК" } // СТУПЕНЬКИ СТУПЕНЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%+МИ" } // СТУПЕНЬКОЙ СТУПЕНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // СТУПЕНЬКУ СТУПЕНЬКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // СТУПЕНЬКЕ СТУПЕНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // СТУПЕНЬКЕ СТУПЕНЬКАХ } paradigm /*СТРЯПНЯ*/ Сущ_2051 : СУЩЕСТВИТЕЛЬНОЕ { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // СТРЯПНЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // СТРЯПНИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЁЙ" } // СТРЯПНЁЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЁЮ" } // СТРЯПНЁЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // СТРЯПНЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // СТРЯПНЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // СТРЯПНЕ } paradigm Анастасия, Сущ_2052 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бИЯ" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // АНАСТАСИЯ АНАСТАСИИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+Й" } // АНАСТАСИИ АНАСТАСИЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // АНАСТАСИЕЙ АНАСТАСИЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+Й" } // АНАСТАСИЮ АНАСТАСИЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+И" "%+М" } // АНАСТАСИИ АНАСТАСИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+И" "%+Х" } // АНАСТАСИИ АНАСТАСИЯХ } paradigm Авдотья, Сущ_2053 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЬЯ" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // АВДОТЬЯ АВДОТЬИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ИЙ" } // АВДОТЬИ АВДОТИЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // АВДОТЬЕЙ АВДОТЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-2%+ИЙ" } // АВДОТЬЮ АВДОТИЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // АВДОТЬЕ АВДОТЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // АВДОТЬЕ АВДОТЬЯХ } paradigm /*ПАШНЯ*/ Сущ_2054: СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+и" } // пашня пашни ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+и" "%-2%+ен" } // пашни пашен ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+еЙ" "%+МИ" } // пашней пашнями ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ею" } // пашнею ПАДЕЖ:ВИН ЧИСЛО { "%-1%+ю" "%-1%+и" } // пашню пашни ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+е" "%+м" } // пашне пашням ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+е" "%+х" } // пашне пашнях } paradigm /*петля*/ Сущ_2055: СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+и" } // петля петли ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+и" "%-2%+ель" } // петли петель ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+еЙ" "%+МИ" } // петлей петлями ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ею" } // петлею ПАДЕЖ:ВИН ЧИСЛО { "%-1%+ю" "%-1%+и" } // петлю петли ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+е" "%+м" } // петле петлям ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+е" "%+х" } // петле петлях } paradigm /*пеня*/ Сущ_2056: СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+и" } // пеня пени ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+и" } // пени ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+еЙ" "%+МИ" } // пеней пенями ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ею" } // пенею ПАДЕЖ:ВИН ЧИСЛО { "%-1%+ю" "%-1%+и" } // пеню пени ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+е" "%+м" } // пене пеням ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+е" "%+х" } // пене пенях } // Отличие от 2010 - в дательном падеже единственного числа paradigm /*ГАЛЕРЕЯ*/ Сущ_2057 : СУЩЕСТВИТЕЛЬНОЕ { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ГАЛЕРЕЯ ГАЛЕРЕИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+Й" } // ГАЛЕРЕИ ГАЛЕРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // ГАЛЕРЕЕЙ ГАЛЕРЕЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ГАЛЕРЕЮ ГАЛЕРЕИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ГАЛЕРЕЕ ГАЛЕРЕЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ГАЛЕРЕЕ ГАЛЕРЕЯХ } paradigm /*МОРЕ*/ Сущ_3001 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Я" } // МОРЕ МОРЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // МОРЯ МОРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+ЯМИ" } // МОРЕМ МОРЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+Я" } // МОРЕ МОРЯ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // МОРЮ МОРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // МОРЕ МОРЯХ } paradigm ПРЕДУПРЕЖДЕНИЕ, Сущ_3003 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИЕ" { РОД:СР ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "" } // предупреждение ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-1%+Я" } // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-1%+ЕМ" } // ПРЕДУПРЕЖДЕНИЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "" } // ПРЕДУПРЕЖДЕНИЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-1%+Ю" } // ПРЕДУПРЕЖДЕНИЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-1%+И" } // ПРЕДУПРЕЖДЕНИИ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:(РОД) ЧИСЛО:Мн { "%-1%+Й" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЙ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-1%+ЯМИ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-1%+ЯМ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-1%+ЯХ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯХ ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "" } // предупрежденье ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-1%+Я" } // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-1%+ЕМ" } // ПРЕДУПРЕЖДЕНЬЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "" } // ПРЕДУПРЕЖДЕНЬЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-1%+Ю" } // ПРЕДУПРЕЖДЕНЬЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-1%+И" } // ПРЕДУПРЕЖДЕНЬИ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-1%+ЯМИ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-1%+ЯМ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-1%+ЯХ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯХ } // существительные типа ПРЕДУПРЕЖДЕНИЕ, имеющие альтернативных набор форм на -ЬЕ paradigm /*ПРЕДУПРЕЖДЕНИЕ*/ Сущ_3003_2 : СУЩЕСТВИТЕЛЬНОЕ { РОД:СР ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "%-2%+ИЕ" } // предупреждение ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-2%+ИЯ" } // ПРЕДУПРЕЖДЕНиЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-2%+ИЕМ" } // ПРЕДУПРЕЖДЕНиЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "%-2%+ИЕ" } // ПРЕДУПРЕЖДЕНиЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-2%+ИЮ" } // ПРЕДУПРЕЖДЕНиЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-2%+ИИ" } // ПРЕДУПРЕЖДЕНиИ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-2%+ИЯ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:(РОД) ЧИСЛО:Мн { "%-2%+ИЙ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЙ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-2%+ИЯМИ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-2%+ИЯ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-2%+ИЯМ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-2%+ИЯХ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯХ ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "%-2%+ЬЕ" } // предупрежденье ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-2%+ЬЯ" } // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-2%+ЬЕМ" } // ПРЕДУПРЕЖДЕНЬЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "%-2%+ЬЕ" } // ПРЕДУПРЕЖДЕНЬЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-2%+ЬЮ" } // ПРЕДУПРЕЖДЕНЬЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-2%+ЬЕ" } // ПРЕДУПРЕЖДЕНЬЕ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-2%+ЬЯ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-2%+ЬЯМИ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-2%+ЬЯ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-2%+ЬЯМ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-2%+ЬЯХ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯХ } paradigm /*КУШАНЬЕ*/ Сущ_3006 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "" } // КУШАНЬЕ ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-1%+Я" } // КУШАНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-1%+ЕМ" } // КУШАНЬЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "" } // КУШАНЬЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-1%+Ю" } // КУШАНЬЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-1%+Е" } // КУШАНЬЕ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // КУШАНЬЯ ПАДЕЖ:(РОД) ЧИСЛО:Мн { "%-2%+ИЙ" } :: flexer "pl" // КУШАНИЙ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-1%+ЯМИ" } :: flexer "pl" // КУШАНЬЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // КУШАНЬЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-1%+ЯМ" } :: flexer "pl" // КУШАНЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-1%+ЯХ" } :: flexer "pl" // КУШАНЬЯХ } paradigm /*ДЕРЕВО*/ Сущ_3007 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+ЬЯ" } // ДЕРЕВО ДЕРЕВЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ЬЕВ" } // ДЕРЕВА ДЕРЕВЬЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+ЬЯМИ" } // ДЕРЕВОМ ДЕРЕВЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+ЬЯ" } // ДЕРЕВО ДЕРЕВЬЯ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+ЬЯМ" } // ДЕРЕВУ ДЕРЕВЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЬЯХ" } // ДЕРЕВЕ ДЕРЕВЬЯХ } paradigm /*УХО*/ Сущ_3008 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ШИ" } // УХО УШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ШЕЙ" } // УХА УШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-2%+ШАМИ" } // УХОМ УШАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ШИ" } // УХО УШИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-2%+ШАМ" } // УХУ УШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-2%+ШАХ" } // УХЕ УШАХ } paradigm ВАРЕВО, Сущ_3009 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бО" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ВАРЕВО ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ВАРЕВА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+М" } // ВАРЕВОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ВАРЕВО ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ВАРЕВУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ВАРЕВЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+А" } :: flexer "pl" // ВАРЕВА ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // ВАРЕВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ВАРЕВАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+А" } :: flexer "pl" // ВАРЕВА ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ВАРЕВАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ВАРЕВАХ } paradigm ИВАНОВО, Сущ_3010 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ВО" { РОД:СР ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ CharCasing:FirstCapitalized ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ИВАНОВО ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ИВАНОВА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЫМ" } // ИВАНОВЫМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ИВАНОВО ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ИВАНОВУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ИВАНОВЕ } paradigm /*КУПЕ*/ Сущ_3012 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ } paradigm /*СЕРДЦЕ*/ Сущ_3013 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // СЕРДЦЕ СЕРДЦА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ЕЦ" } // СЕРДЦА СЕРДЕЦ ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // СЕРДЦЕМ СЕРДЦЕМ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // СЕРДЦЕ СЕРДЦА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // СЕРДЦУ СЕРДЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // СЕРДЦЕ СЕРДЦАХ } paradigm /*СТЕКЛО*/ Сущ_3014 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁКЛА" } // СТЕКЛО СТЁКЛА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-3%+ЁКЛ" } // СТЕКЛА СТЁКОЛ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-3%+ЁКЛАМИ" } // СТЕКЛОМ СТЁКЛАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+ЁКЛА" } // СТЕКЛО СТЁКЛА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-3%+ЁКЛАМ" } // СТЕКЛУ СТЁКЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁКЛАХ" } // СТЕКЛЕ СТЁКЛАХ } paradigm /*ЯЙЦО*/ Сущ_3015 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // ЯЙЦО ЯЙЦА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-3%+ИЦ" } // ЯЙЦА ЯИЦ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+АМИ" } // ЯЙЦОМ ЯЙЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // ЯЙЦО ЯЙЦА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ЯЙЦУ ЯЙЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ЯЙЦЕ ЯЙЦАХ } paradigm /*УТРО*/ Сущ_3016 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // УТРО ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // УТРА ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+АМИ" } // УТРОМ УТРАМИ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // УТРО ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // УТРУ УТРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // УТРЕ УТРАХ } paradigm /*БЕЛЬЁ*/ Сущ_3017 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // БЕЛЬЁ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // БЕЛЬЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+М" } // БЕЛЬЁМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // БЕЛЬЁ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // БЕЛЬЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Ё" } // БЕЛЬЁ } paradigm /*КОЛЕНО*/ Сущ_3018 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КОЛЕНО КОЛЕНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ЕЙ" } // КОЛЕНА КОЛЕНЕЙ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } // КОЛЕН ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+ЯМИ" } // КОЛЕНОМ КОЛЕНЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // КОЛЕНО КОЛЕНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+ЯМ" } // КОЛЕНУ КОЛЕНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // КОЛЕНЕ КОЛЕНЯХ } paradigm /*ПЛЕЧО*/ Сущ_3019 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ПЛЕЧО ПЛЕЧИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ЕЙ" } // ПЛЕЧА ПЛЕЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+АМИ" } // ПЛЕЧОМ ПЛЕЧАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // ПЛЕЧО ПЛЕЧИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ПЛЕЧУ ПЛЕЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ПЛЕЧЕ ПЛЕЧАХ } paradigm /*ГОРЕ*/ Сущ_3021 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГОРЕ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // ГОРЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+Е" } // ГОРЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ГОРЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // ГОРЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГОРЕ } paradigm /*ЧЕЛО*/ Сущ_3022 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЧЕЛО ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ЧЕЛА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+М" } // ЧЕЛОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЧЕЛО ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ЧЕЛУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ЧЕЛЕ } paradigm /*ПЛАТЬЕ*/ Сущ_3023 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Я" } // ПЛАТЬЕ ПЛАТЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%+В" } // ПЛАТЬЯ ПЛАТЬЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // ПЛАТЬЕМ ПЛАТЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+Я" } // ПЛАТЬЕ ПЛАТЬЯ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Я" "%-1%+ЯМ" } // ПЛАТЬЯ ПЛАТЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "" "%-1%+ЯХ" } // ПЛАТЬЕ ПЛАТЬЯХ } paradigm /*ВЕКО*/ Сущ_3024 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ВЕКО ВЕКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1" } // ВЕКА ВЕК ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // ВЕКОМ ВЕКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // ВЕКО ВЕКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ВЕКУ ВЕКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ВЕКЕ ВЕКАХ } paradigm /*ПЯТНО*/ Сущ_3025 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // ПЯТНО ПЯТНА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ЕН" } // ПЯТНА ПЯТЕН ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // ПЯТНОМ ПЯТНАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // ПЯТНО ПЯТНА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ПЯТНУ ПЯТНАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ПЯТНЕ ПЯТНАХ } paradigm /*НЕБО*/ Сущ_3027 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+ЕСА" } // НЕБО НЕБЕСА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ЕС" } // НЕБА НЕБЕС ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+ЕСАМИ" } // НЕБОМ НЕБЕСАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+ЕСА" } // НЕБО НЕБЕСА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+ЕСАМ" } // НЕБУ НЕБЕСАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЕСАХ" } // НЕБЕ НЕБЕСАХ } paradigm /*КОПЬЁ*/ Сущ_3029 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Я" } // КОПЬЁ КОПЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-2%+ИЙ" } // КОПЬЯ КОПИЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // КОПЬЁМ КОПЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+Я" } // КОПЬЁ КОПЬЯ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // КОПЬЮ КОПЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // КОПЬЕ КОПЬЯХ } paradigm /*ЖИВОТНОЕ*/ Сущ_3030 : СУЩЕСТВИТЕЛЬНОЕ { РОД:СР ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЫЕ" } // ЖИВОТНОЕ ЖИВОТНЫЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+ГО" "%-2%+ЫХ" } // ЖИВОТНОГО ЖИВОТНЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЫМ" "%-2%+ЫМИ" } // ЖИВОТНЫМ ЖИВОТНЫМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЫХ" } // ЖИВОТНОЕ ЖИВОТНЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+МУ" "%-2%+ЫМ" } // ЖИВОТНОМУ ЖИВОТНЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+М" "%-2%+ЫХ" } // ЖИВОТНОМ ЖИВОТНЫХ } paradigm /*ОБЛАКО*/ Сущ_3031 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // ОБЛАКО ОБЛАКА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ОВ" } // ОБЛАКА ОБЛАКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // ОБЛАКОМ ОБЛАКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // ОБЛАКО ОБЛАКА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ОБЛАКУ ОБЛАКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ОБЛАКЕ ОБЛАКАХ } paradigm /*ОЗЕРО*/ Сущ_3033 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁРА" } // ОЗЕРО ОЗЁРА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-3%+ЁР" } // ОЗЕРА ОЗЁР ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-3%+ЁРАМИ" } // ОЗЕРОМ ОЗЁРАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+ЁРА" } // ОЗЕРО ОЗЁРА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-3%+ЁРАМ" } // ОЗЕРУ ОЗЁРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁРАХ" } // ОЗЕРЕ ОЗЁРАХ } paradigm /*КОЛЕСО*/ Сущ_3034 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁСА" } // КОЛЕСО КОЛЁСА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-3%+ЁС" } // КОЛЕСА КОЛЁС ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-3%+ЁСАМИ" } // КОЛЕСОМ КОЛЁСАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+ЁСА" } // КОЛЕСО КОЛЁСА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-3%+ЁСАМ" } // КОЛЕСУ КОЛЁСАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁСАХ" } // КОЛЕСЕ КОЛЁСАХ } paradigm /*КЛАДБИЩЕ*/ Сущ_3035 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // КЛАДБИЩЕ КЛАДБИЩА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1" } // КЛАДБИЩА КЛАДБИЩ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+АМИ" } // КЛАДБИЩЕМ КЛАДБИЩАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // КЛАДБИЩЕ КЛАДБИЩА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // КЛАДБИЩУ КЛАДБИЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // КЛАДБИЩЕ КЛАДБИЩАХ } paradigm /*ГНЕЗДО*/ Сущ_3036 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-4%+ЁЗДА" } // ГНЕЗДО ГНЁЗДА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-4%+ЁЗД" } // ГНЕЗДА ГНЁЗД ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-4%+ЁЗДАМИ" } // ГНЕЗДОМ ГНЁЗДАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-4%+ЁЗДА" } // ГНЕЗДО ГНЁЗДА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-4%+ЁЗДАМ" } // ГНЕЗДУ ГНЁЗДАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-4%+ЁЗДАХ" } // ГНЕЗДЕ ГНЁЗДАХ } paradigm /*МЕСТЕЧКО*/ Сущ_3037 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // МЕСТЕЧКО МЕСТЕЧКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ЕК" } // МЕСТЕЧКА МЕСТЕЧЕК ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // МЕСТЕЧКОМ МЕСТЕЧКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // МЕСТЕЧКО МЕСТЕЧКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // МЕСТЕЧКУ МЕСТЕЧКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // МЕСТЕЧКЕ МЕСТЕЧКАХ } paradigm /*ЯДРО*/ Сущ_3038 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // ЯДРО ЯДРА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ЕР" } // ЯДРА ЯДЕР ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // ЯДРОМ ЯДРАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // ЯДРО ЯДРА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ЯДРУ ЯДРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ЯДРЕ ЯДРАХ } paradigm /*САНИ*/ Сущ_4001 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // САНИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕЙ" } // САНЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } // САНЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // САНИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } // САНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } // САНЯХ } paradigm /*ЦВЕТЫ*/ Сущ_4003 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // --- ЦВЕТЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ОВ" } // --- ЦВЕТОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // --- ЦВЕТАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+Ы" } // --- ЦВЕТЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // --- ЦВЕТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // --- ЦВЕТАХ } paradigm /*НОЖНИЦЫ*/ Сущ_4004 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // НОЖНИЦЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } // НОЖНИЦ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // НОЖНИЦАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // НОЖНИЦЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // НОЖНИЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // НОЖНИЦАХ } paradigm /*ОЧКИ*/ Сущ_4005 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // ОЧКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ОВ" } // ОЧКОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // ОЧКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // ОЧКИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // ОЧКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // ОЧКАХ } paradigm /*ВОРОТА*/ Сущ_4006 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // ВОРОТА ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } // ВОРОТ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } // ВОРОТАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // ВОРОТА ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } // ВОРОТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } // ВОРОТАХ } paradigm /*ГРАФФИТИ*/ Сущ_4007 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } ПАДЕЖ:ВИН ЧИСЛО:МН { "" } ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } } paradigm /*МОЩИ*/ Сущ_4008 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // МОЩИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕЙ" } // МОЩЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // МОЩАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // МОЩИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // МОЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // МОЩАХ } // слова без парадигмы paradigm /**/ Сущ_4010 : СУЩЕСТВИТЕЛЬНОЕ { РОД:СР ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // } paradigm Полрюмки, Сущ_4011 : СУЩЕСТВИТЕЛЬНОЕ { ОДУШ:НЕОДУШ ПЕРЕЧИСЛИМОСТЬ:ДА РОД:СР ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // полрюмки ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // полрюмки ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // полрюмки } // ****************************************************** // Далее идут автоматические парадигмы для стеммера // ****************************************************** paradigm МЕХАНОШВИЛИ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ШВИЛИ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { ""} } paradigm ЮЩЕНКО : СУЩЕСТВИТЕЛЬНОЕ for "(.+)НКО" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { ""} } paradigm ИВАНОВА /*(женская фамилия)*/ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ОВА" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // ИВАНОВА ИВАНОВЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+ОЙ" "%-1%+ЫХ" } // ИВАНОВОЙ ИВАНОВЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+ЫМИ" } // ИВАНОВОЙ ИВАНОВЫМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+ЫХ" } // ИВАНОВУ ИВАНОВЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+ОЙ" "%-1%+ЫМ" } // ИВАНОВОЙ ИВАНОВЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+ОЙ" "%-1%+ЫХ" } // ИВАНОВОЙ ИВАНОВЫХ } paradigm ПАПАНЕСКУ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)СКУ" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } } paradigm ИВАНОВ /*(мужская фамилия)*/ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ОВ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // ИВАНОВ ИВАНОВЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЫХ" } // ИВАНОВА ИВАНОВЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЫМ" "%+ЫМИ" } // ИВАНОВЫМ ИВАНОВЫМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЫХ" } // ИВАНОВА ИВАНОВЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЫМ" } // ИВАНОВУ ИВАНОВЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЫХ" } // ИВАНОВЕ ИВАНОВЫХ } // Последняя в списке - парадигма для самого частого склонения paradigm ФАЙЛ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[БВДЗЛМНПРСТФЦ]" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // ФАЙЛ ФАЙЛЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ФАЙЛА ФАЙЛОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ФАЙЛОМ ФАЙЛАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+Ы" } // ФАЙЛ ФАЙЛЫ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ФАЙЛУ ФАЙЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ФАЙЛЕ ФАЙЛАХ } // Вариант самого частого склонения - для одушевленных существительных paradigm ТАНЦОР : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[БВДЗЛМНПРСТФЦ]" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // ОПЕРАТОР ОПЕРАТОРЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ОПЕРАТОРА ОПЕРАТОРОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ОПЕРАТОРОМ ОПЕРАТОРАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ОВ" } // ОПЕРАТОРА ОПЕРАТОРОВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ОПЕРАТОРУ ОПЕРАТОРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ОПЕРАТОРЕ ОПЕРАТОРАХ } }
ОГОНЁК ОГОНЬКИ
ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЬКИ" }
5,383,408
[ 1, 145, 257, 145, 246, 145, 257, 145, 256, 145, 228, 145, 253, 565, 225, 145, 257, 145, 246, 145, 257, 145, 256, 145, 110, 145, 253, 145, 251, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 225, 145, 258, 145, 243, 145, 247, 145, 248, 145, 249, 30, 145, 245, 145, 251, 145, 256, 377, 225, 145, 105, 145, 251, 145, 99, 145, 254, 145, 257, 288, 1408, 1850, 2213, 17, 22, 9, 15, 145, 110, 145, 253, 145, 251, 6, 282, 289, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/288/0xc71c3C179B0552065dBbCE26B391d42a742145ef/sources/contracts/Ola/Peripheral/PriceOracle/open-oracle/Uniswap/UniswapAnchoredView.sol
* @notice Get the underlying price of a cToken @dev Implements the PriceOracle interface for Compound v2. @param cToken The cToken address for price retrieval @return Price denominated in USD, with 18 decimals, for the given cToken address/
function getUnderlyingPrice(address cToken) external view returns (uint) { return getAssetPriceInternal(CErc20ForUniswapConfig(cToken).underlying()); }
16,906,430
[ 1, 967, 326, 6808, 6205, 434, 279, 276, 1345, 225, 29704, 326, 20137, 23601, 1560, 364, 21327, 331, 22, 18, 225, 276, 1345, 1021, 276, 1345, 1758, 364, 6205, 22613, 327, 20137, 10716, 7458, 316, 587, 9903, 16, 598, 6549, 15105, 16, 364, 326, 864, 276, 1345, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10833, 765, 6291, 5147, 12, 2867, 276, 1345, 13, 3903, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 24689, 5147, 3061, 12, 1441, 1310, 3462, 1290, 984, 291, 91, 438, 809, 12, 71, 1345, 2934, 9341, 6291, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/Strings.sol'; import './CAIC.sol'; import './Randomize.sol'; import "./IBMP.sol"; /// @title CaicGrids /// @author tfs128 (@trickerfs128) contract CaicGrids is CAIC { using Strings for uint256; using Strings for uint32; using Randomize for Randomize.Random; IBMP public immutable _bmp; /// @notice constructor /// @param contractURI can be empty /// @param openseaProxyRegistry can be address zero /// @param bmp encoder address constructor( string memory contractURI, address openseaProxyRegistry, address bmp ) CAIC(contractURI, openseaProxyRegistry) { _bmp = IBMP(bmp); } /// @dev Rendering function; should be overrode /// @param tokenId the tokenId /// @param seed the seed /// @param isSvg true=svg, false=base64 encoded function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view override returns (string memory) { Randomize.Random memory random = Randomize.Random({ seed: uint256(seed), offsetBit: 0 }); uint256 rule = random.next(1,255); bytes memory pixels = getCells(rule,random); bytes memory bmpImage = _bmp.bmp(pixels,SIZE,SIZE,_bmp.grayscale()); if(isSvg == true) { string memory sizeInString = SIZE.toString(); bytes memory image = abi.encodePacked( '"image":"data:image/svg+xml;utf8,', "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' height='",sizeInString,"' width='",sizeInString,"'>" "<image style='image-rendering: pixelated;' height='",sizeInString,"' width='",sizeInString,"' xlink:href='",_bmp.bmpDataURI(bmpImage),"'></image>", '</svg>"' ); return string(abi.encodePacked( 'data:application/json;utf8,' '{"name":"Grid #',tokenId.toString(),'",', '"description":"A grid completely generated onchain using 1D cellular automaton.",', '"properties":{ "Rule":"',rule.toString(),'"},', image, '}' )); } else { return string(abi.encodePacked( _bmp.bmpDataURI(bmpImage) )); } } /// @notice Gas eater function, to generate cells on grid /// @param rule CA rule 1-255 /// @param random to generate random initial row. function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; if(SIZE <= 256) { increment = 3; } else if(SIZE <= 384) { increment = 2; } else { increment = 1; } for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './BaseOpenSea.sol'; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /// @title CAIC (Cellular Automaton In Chain) /// @author Tfs128 (@trickerfs128) /// @dev most of the code borrowed from [sol]Seedlings contract written by Simon Fremaux (@dievardump) contract CAIC is BaseOpenSea, ERC721Enumerable,Ownable,ReentrancyGuard { event SeedChangeRequest(uint256 indexed tokenId, address indexed operator); event Collected(address indexed operator, uint256 indexed count,uint256 value); event Claimed(address indexed operator); event SizeUpdated(uint32 size); // Last Token Id Generated. uint256 public LAST_TOKEN_ID; //public minting start time. uint256 public PUBLIC_MINTING_TIME = block.timestamp + 36 hours; // 0.00768 uint256 public PRICE = 7680000000000000; // Max Available for mint `Available` - `Reserved` uint256 public AVAILABLE = 509; // 257 reserved for blockglyphs holders + 2 for owner uint256 public BG_RESERVED_LEFT = 259; // Max mints allowed in single transaction uint256 public MAX_MINT = 11; // Last Seed Generated bytes32 public LAST_SEED; // Size of image height:=SIZE, width:=SIZE uint32 public SIZE = 256; // each token seed mapping(uint256 => bytes32) internal _tokenSeed; // tokenIds with a request for seeds change mapping(uint256 => bool) private _seedChangeRequests; // blockGlyph holders mapping(address => bool) public _bgHolders; /// @notice constructor /// @param contractURI can be empty /// @param openseaProxyRegistry can be address zero constructor( string memory contractURI, address openseaProxyRegistry ) ERC721('CAIC', 'CAIC') { //CAIC (Cellular Automaton In Chain) if (bytes(contractURI).length > 0) { _setContractURI(contractURI); } if (address(0) != openseaProxyRegistry) { _setOpenSeaRegistry(openseaProxyRegistry); } } /// @notice function to mint `count` token(s) to `msg.sender` /// @param count numbers of tokens function mint(uint256 count) external payable nonReentrant { require (block.timestamp >= PUBLIC_MINTING_TIME, 'Wait'); require(count > 0, 'Must be greater than 0'); require(count <= MAX_MINT, 'More Than Max Allowed.' ); require(count <= AVAILABLE, 'Too Many Requested.'); require(msg.value == PRICE * count , 'Not Enough Amount.'); uint256 tokenId = LAST_TOKEN_ID; bytes32 blockHash = blockhash(block.number - 1); bytes32 nextSeed; for (uint256 i; i < count; i++) { tokenId++; _safeMint(msg.sender, tokenId); nextSeed = keccak256( abi.encodePacked( LAST_SEED, block.timestamp, msg.sender, blockHash, block.coinbase, block.difficulty, tx.gasprice ) ); LAST_SEED = nextSeed; _tokenSeed[tokenId] = nextSeed; } LAST_TOKEN_ID = tokenId; AVAILABLE -= count; emit Collected(msg.sender, count, msg.value); } /// @notice func for free token claim for blockglyph holders function claim() external { require (block.timestamp < PUBLIC_MINTING_TIME, 'You are late.'); //I had made a blunder in previouse deployment, so had to redeploy again. //rather than storing whole reserve list again, will use it from //previouse contract. require (CAIC(0xb742848B5971cE5D0628E351714AF5F1F4e4A8A2)._bgHolders(msg.sender) == true, 'Not a bg holder.'); require (_bgHolders[msg.sender] == false , 'Already claimed.'); uint256 tokenId = LAST_TOKEN_ID + 1; _safeMint(msg.sender, tokenId); bytes32 blockHash = blockhash(block.number - 1); bytes32 nextSeed = keccak256( abi.encodePacked( LAST_SEED, block.timestamp, msg.sender, blockHash, block.coinbase, block.difficulty, tx.gasprice ) ); LAST_TOKEN_ID = tokenId; LAST_SEED = nextSeed; _tokenSeed[tokenId] = nextSeed; BG_RESERVED_LEFT -= 1; _bgHolders[msg.sender] = true; emit Claimed(msg.sender); } /// @notice function to request seed change by token owner. /// @param tokenId of which seed change requested function requestSeedChange(uint256 tokenId) external { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); _seedChangeRequests[tokenId] = true; emit SeedChangeRequest(tokenId, msg.sender); } /// opensea config (https://docs.opensea.io/docs/contract-level-metadata) function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } ///@notice function to update image res ///@param imageSize height X width = 'imageSize * imageSize' function updateImageSize(uint32 imageSize) external onlyOwner { require(imageSize % 4 == 0, 'Should be a multiple of 4'); require(imageSize > 63 && imageSize < 513, 'Must be between 64-512'); SIZE = imageSize; emit SizeUpdated(imageSize); } /// @dev blockglyphs holders struct. struct bgHolderAddresses { address addr; bool available; } /// @notice function to add blockglyph holders + 2 owner reserved function addBgHolders(bgHolderAddresses[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _bgHolders[addresses[i].addr] = addresses[i].available; } } ///@notice function to respond to seed change requests ///@param tokenId of which seed needs to be change function changeSeedAfterRequest(uint256 tokenId) external onlyOwner { require(_seedChangeRequests[tokenId] == true, 'No request for token.'); _seedChangeRequests[tokenId] = false; _tokenSeed[tokenId] = keccak256( abi.encode( _tokenSeed[tokenId], block.timestamp, block.difficulty, blockhash(block.number - 1) ) ); } /// @notice function to withdraw balance. function withdraw() external onlyOwner { require(address(this).balance > 0, "0 Balance."); bool success; (success, ) = msg.sender.call{value: address(this).balance}(''); require(success, 'Failed'); } /// @notice this function returns the seed associated to a tokenId /// @param tokenId to get the seed of function getTokenSeed(uint256 tokenId) external view returns (bytes32) { require(_exists(tokenId), 'TokenSeed query for nonexistent token'); return _tokenSeed[tokenId]; } /// @notice function to get raw based64 encoded image /// @param tokenId id of token function getRaw(uint256 tokenId) public view returns (string memory) { require( _exists(tokenId), 'Query for nonexistent token' ); return _render(tokenId, _tokenSeed[tokenId],false); } /// @notice tokenURI override that returns a data:json application /// @inheritdoc ERC721 function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); return _render(tokenId, _tokenSeed[tokenId],true); } /// @notice Called with the sale price to determine how much royalty /// @param tokenId - the NFT asset queried for royalty information /// @param value - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 tokenId, uint256 value) public view returns (address receiver, uint256 royaltyAmount) { receiver = owner(); royaltyAmount = (value * 300) / 10000; } /// @notice Function allowing to check the rendering for a given seed /// @param seed the seed to render function renderSeed(bytes32 seed) public view returns (string memory) { return _render(1, seed, false); } /// @dev Rendering function; /// @param tokenId which needs to be render /// @param seed seed which needs to be render /// @param isSvg true=svg, false=base64 encoded function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view virtual returns (string memory) { seed; return string( abi.encodePacked( 'data:application/json,{"name":"', tokenId, '"}' ) ); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // small library to randomize using (min, max, seed, offsetBit etc...) library Randomize { struct Random { uint256 seed; uint256 offsetBit; } /// @notice get an random number between (min and max) using seed and offseting bits /// this function assumes that max is never bigger than 0xffffff (hex color with opacity included) /// @dev this function is simply used to get random number using a seed. /// if does bitshifting operations to try to reuse the same seed as much as possible. /// should be enough for anyth /// @param random the randomizer /// @param min the minimum /// @param max the maximum /// @return result the resulting pseudo random number function next( Random memory random, uint256 min, uint256 max ) internal pure returns (uint256 result) { uint256 newSeed = random.seed; uint256 newOffset = random.offsetBit + 3; uint256 maxOffset = 4; uint256 mask = 0xf; if (max > 0xfffff) { mask = 0xffffff; maxOffset = 24; } else if (max > 0xffff) { mask = 0xfffff; maxOffset = 20; } else if (max > 0xfff) { mask = 0xffff; maxOffset = 16; } else if (max > 0xff) { mask = 0xfff; maxOffset = 12; } else if (max > 0xf) { mask = 0xff; maxOffset = 8; } // if offsetBit is too high to get the max number // just get new seed and restart offset to 0 if (newOffset > (256 - maxOffset)) { newOffset = 0; newSeed = uint256(keccak256(abi.encode(newSeed))); } uint256 offseted = (newSeed >> newOffset); uint256 part = offseted & mask; result = min + (part % (max - min)); random.seed = newSeed; random.offsetBit = newOffset; } function nextInt( Random memory random, uint256 min, uint256 max ) internal pure returns (int256 result) { result = int256(Randomize.next(random, min, max)); } } // SPDX-License-Identifier: MIT // Copyright 2021 Arran Schlosberg / Twitter @divergence_art pragma solidity >=0.8.0 <0.9.0; /// @title IBMP interface /// @dev interface of BMP.sol originally used in brotchain (0xd31fc221d2b0e0321c43e9f6824b26ebfff01d7d) interface IBMP { /// @notice Returns an 8-bit grayscale palette for bitmap images. function grayscale() external pure returns (bytes memory); /// @notice Returns an 8-bit BMP encoding of the pixels. /// @param pixels bytes array of pixels /// @param width - /// @param height - /// @param palette bytes array function bmp(bytes memory pixels, uint32 width, uint32 height, bytes memory palette) external pure returns (bytes memory); /// @notice Returns the buffer, presumably from bmp(), as a base64 data URI. /// @param bmpBuf encoded bytes of pixels function bmpDataURI(bytes memory bmpBuf) external pure returns (string memory); /// @notice Scale pixels by repetition along both axes. /// @param pixels bytes array of pixels /// @param width - /// @param height - /// @param scale - function scalePixels(bytes memory pixels, uint32 width, uint32 height, uint32 scale) external pure returns (bytes memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's support contract BaseOpenSea { string private _contractURI; ProxyRegistry private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Helper for OpenSea gas-less trading /// @dev Allows to check if `operator` is owner's OpenSea proxy /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { ProxyRegistry proxyRegistry = _proxyRegistry; return // we have a proxy registry address address(proxyRegistry) != address(0) && // current operator is owner's proxy address address(proxyRegistry.proxies(owner)) == operator; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = ProxyRegistry(proxyRegistryAddress); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT 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; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. 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 || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _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 || ERC721.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 { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
@title CaicGrids @author tfs128 (@trickerfs128)
contract CaicGrids is CAIC { using Strings for uint256; using Strings for uint32; using Randomize for Randomize.Random; IBMP public immutable _bmp; constructor( string memory contractURI, address openseaProxyRegistry, address bmp pragma solidity ^0.8.0; ) CAIC(contractURI, openseaProxyRegistry) { _bmp = IBMP(bmp); } function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view override returns (string memory) { Randomize.Random memory random = Randomize.Random({ seed: uint256(seed), offsetBit: 0 }); uint256 rule = random.next(1,255); bytes memory pixels = getCells(rule,random); bytes memory bmpImage = _bmp.bmp(pixels,SIZE,SIZE,_bmp.grayscale()); if(isSvg == true) { string memory sizeInString = SIZE.toString(); bytes memory image = abi.encodePacked( '"image":"data:image/svg+xml;utf8,', "<image style='image-rendering: pixelated;' height='",sizeInString,"' width='",sizeInString,"' xlink:href='",_bmp.bmpDataURI(bmpImage),"'></image>", '</svg>"' ); return string(abi.encodePacked( 'data:application/json;utf8,' '{"name":"Grid #',tokenId.toString(),'",', '"description":"A grid completely generated onchain using 1D cellular automaton.",', image, '}' )); } else { return string(abi.encodePacked( _bmp.bmpDataURI(bmpImage) )); } } function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view override returns (string memory) { Randomize.Random memory random = Randomize.Random({ seed: uint256(seed), offsetBit: 0 }); uint256 rule = random.next(1,255); bytes memory pixels = getCells(rule,random); bytes memory bmpImage = _bmp.bmp(pixels,SIZE,SIZE,_bmp.grayscale()); if(isSvg == true) { string memory sizeInString = SIZE.toString(); bytes memory image = abi.encodePacked( '"image":"data:image/svg+xml;utf8,', "<image style='image-rendering: pixelated;' height='",sizeInString,"' width='",sizeInString,"' xlink:href='",_bmp.bmpDataURI(bmpImage),"'></image>", '</svg>"' ); return string(abi.encodePacked( 'data:application/json;utf8,' '{"name":"Grid #',tokenId.toString(),'",', '"description":"A grid completely generated onchain using 1D cellular automaton.",', image, '}' )); } else { return string(abi.encodePacked( _bmp.bmpDataURI(bmpImage) )); } } function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view override returns (string memory) { Randomize.Random memory random = Randomize.Random({ seed: uint256(seed), offsetBit: 0 }); uint256 rule = random.next(1,255); bytes memory pixels = getCells(rule,random); bytes memory bmpImage = _bmp.bmp(pixels,SIZE,SIZE,_bmp.grayscale()); if(isSvg == true) { string memory sizeInString = SIZE.toString(); bytes memory image = abi.encodePacked( '"image":"data:image/svg+xml;utf8,', "<image style='image-rendering: pixelated;' height='",sizeInString,"' width='",sizeInString,"' xlink:href='",_bmp.bmpDataURI(bmpImage),"'></image>", '</svg>"' ); return string(abi.encodePacked( 'data:application/json;utf8,' '{"name":"Grid #',tokenId.toString(),'",', '"description":"A grid completely generated onchain using 1D cellular automaton.",', image, '}' )); } else { return string(abi.encodePacked( _bmp.bmpDataURI(bmpImage) )); } } function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view override returns (string memory) { Randomize.Random memory random = Randomize.Random({ seed: uint256(seed), offsetBit: 0 }); uint256 rule = random.next(1,255); bytes memory pixels = getCells(rule,random); bytes memory bmpImage = _bmp.bmp(pixels,SIZE,SIZE,_bmp.grayscale()); if(isSvg == true) { string memory sizeInString = SIZE.toString(); bytes memory image = abi.encodePacked( '"image":"data:image/svg+xml;utf8,', "<image style='image-rendering: pixelated;' height='",sizeInString,"' width='",sizeInString,"' xlink:href='",_bmp.bmpDataURI(bmpImage),"'></image>", '</svg>"' ); return string(abi.encodePacked( 'data:application/json;utf8,' '{"name":"Grid #',tokenId.toString(),'",', '"description":"A grid completely generated onchain using 1D cellular automaton.",', image, '}' )); } else { return string(abi.encodePacked( _bmp.bmpDataURI(bmpImage) )); } } '"properties":{ "Rule":"',rule.toString(),'"},', function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view override returns (string memory) { Randomize.Random memory random = Randomize.Random({ seed: uint256(seed), offsetBit: 0 }); uint256 rule = random.next(1,255); bytes memory pixels = getCells(rule,random); bytes memory bmpImage = _bmp.bmp(pixels,SIZE,SIZE,_bmp.grayscale()); if(isSvg == true) { string memory sizeInString = SIZE.toString(); bytes memory image = abi.encodePacked( '"image":"data:image/svg+xml;utf8,', "<image style='image-rendering: pixelated;' height='",sizeInString,"' width='",sizeInString,"' xlink:href='",_bmp.bmpDataURI(bmpImage),"'></image>", '</svg>"' ); return string(abi.encodePacked( 'data:application/json;utf8,' '{"name":"Grid #',tokenId.toString(),'",', '"description":"A grid completely generated onchain using 1D cellular automaton.",', image, '}' )); } else { return string(abi.encodePacked( _bmp.bmpDataURI(bmpImage) )); } } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } if(SIZE <= 256) { increment = 3; } else if(SIZE <= 384) { increment = 2; } else { increment = 1; } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } }
13,390,695
[ 1, 23508, 335, 6313, 87, 225, 268, 2556, 10392, 261, 36, 313, 5448, 2556, 10392, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 23318, 335, 6313, 87, 353, 6425, 2871, 288, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 565, 1450, 8139, 364, 2254, 1578, 31, 203, 565, 1450, 8072, 554, 364, 8072, 554, 18, 8529, 31, 203, 203, 565, 23450, 4566, 1071, 11732, 389, 70, 1291, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 6835, 3098, 16, 203, 3639, 1758, 1696, 307, 69, 3886, 4243, 16, 203, 3639, 1758, 324, 1291, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 262, 6425, 2871, 12, 16351, 3098, 16, 1696, 307, 69, 3886, 4243, 13, 288, 203, 3639, 389, 70, 1291, 273, 23450, 4566, 12, 70, 1291, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 5902, 12, 11890, 5034, 1147, 548, 16, 1731, 1578, 5009, 16, 1426, 11604, 20105, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 8072, 554, 18, 8529, 3778, 2744, 273, 8072, 554, 18, 8529, 12590, 203, 5411, 5009, 30, 2254, 5034, 12, 12407, 3631, 203, 5411, 1384, 5775, 30, 374, 203, 3639, 15549, 203, 3639, 2254, 5034, 1720, 273, 2744, 18, 4285, 12, 21, 16, 10395, 1769, 203, 3639, 1731, 3778, 8948, 273, 16458, 87, 12, 5345, 16, 9188, 1769, 203, 3639, 1731, 3778, 324, 1291, 2040, 273, 389, 70, 1291, 18, 70, 1291, 12, 21084, 16, 4574, 16, 4574, 16, 67, 70, 1291, 18, 22440, 5864, 10663, 203, 3639, 309, 12, 291, 55, 20105, 422, 638, 13, 288, 203, 2 ]
pragma solidity ^0.8.0; uint constant foo = 1; struct gfoo { uint x; } enum gbar { A } function gf1() { } contract Foo { struct foo { uint x; } enum bar { A } event boo(); function f1(uint x) internal {} uint gfoo; uint gbar; uint gf1; function main(uint foo, uint bar, uint boo, uint f1) public { // Arguments shadowing defintions from the contract level //foo memory m; - can't access struct of same name //bar b; - can't access enum of same name //emit boo(); - can't access event of same name //f1(); - can't access function of same name // State vars shadowing definitions from the unit level //gfoo memory m; - can't access struct from global context shadowed by state var // gbar e; can't access enum from global context shadowed by state var // gf1(); - can't access free function from global context shadowed by state var } }
Arguments shadowing defintions from the contract levelfoo memory m; - can't access struct of same namebar b; - can't access enum of same nameemit boo(); - can't access event of same namef1(); - can't access function of same name State vars shadowing definitions from the unit levelgfoo memory m; - can't access struct from global context shadowed by state var gbar e; can't access enum from global context shadowed by state var gf1(); - can't access free function from global context shadowed by state var
function main(uint foo, uint bar, uint boo, uint f1) public { }
5,399,639
[ 1, 4628, 10510, 310, 1652, 474, 1115, 628, 326, 6835, 1801, 11351, 3778, 312, 31, 300, 848, 1404, 2006, 1958, 434, 1967, 508, 3215, 324, 31, 300, 848, 1404, 2006, 2792, 434, 1967, 508, 18356, 800, 83, 5621, 300, 848, 1404, 2006, 871, 434, 1967, 508, 74, 21, 5621, 300, 848, 1404, 2006, 445, 434, 1967, 508, 3287, 4153, 10510, 310, 6377, 628, 326, 2836, 1801, 75, 11351, 3778, 312, 31, 300, 848, 1404, 2006, 1958, 628, 2552, 819, 10510, 329, 635, 919, 569, 314, 3215, 425, 31, 848, 1404, 2006, 2792, 628, 2552, 819, 10510, 329, 635, 919, 569, 13828, 21, 5621, 300, 848, 1404, 2006, 4843, 445, 628, 2552, 819, 10510, 329, 635, 919, 569, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2774, 12, 11890, 8431, 16, 2254, 4653, 16, 2254, 800, 83, 16, 2254, 284, 21, 13, 1071, 288, 203, 540, 203, 540, 203, 540, 203, 540, 203, 540, 203, 540, 203, 540, 203, 540, 203, 540, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xd73be539d6b2076bab83ca6ba62dfe189abc6bbe //Contract name: BlockchainCutiesCore //Balance: 20.223731891324013681 Ether //Verification Date: 4/25/2018 //Transacion Count: 8014 // CODE STARTS HERE pragma solidity ^0.4.20; /// BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain. /// https://blockchaincuties.co/ /// @title defined the interface that will be referenced in main Cutie contract contract GeneMixerInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneMixer() external pure returns (bool); /// @dev given genes of cutie 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of dad /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2) public view returns (uint256); function canBreed(uint40 momId, uint256 genes1, uint40 dadId, uint256 genes2) public view returns (bool); } /// @author https://BlockChainArchitect.iocontract Bank is CutiePluginBase contract PluginInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPluginInterface() public pure returns (bool); function onRemove() public; /// @dev Begins new feature. /// @param _cutieId - ID of token to auction, sender must be owner. /// @param _parameter - arbitrary parameter /// @param _seller - Old owner, if not the message sender function run( uint40 _cutieId, uint256 _parameter, address _seller ) public payable; /// @dev Begins new feature, approved and signed by COO. /// @param _cutieId - ID of token to auction, sender must be owner. /// @param _parameter - arbitrary parameter function runSigned( uint40 _cutieId, uint256 _parameter, address _owner ) external payable; function withdraw() public; } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract MarketInterface { function withdrawEthFromBalance() external; function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable; function bid(uint40 _cutieId) public payable; function cancelActiveAuctionWhenPaused(uint40 _cutieId) public; function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee ); } /// @title BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain. /// @author https://BlockChainArchitect.io /// @dev This is the BlockchainCuties configuration. It can be changed redeploying another version. contract ConfigInterface { function isConfig() public pure returns (bool); function getCooldownIndexFromGeneration(uint16 _generation) public view returns (uint16); function getCooldownEndTimeFromIndex(uint16 _cooldownIndex) public view returns (uint40); function getCooldownIndexCount() public view returns (uint256); function getBabyGen(uint16 _momGen, uint16 _dadGen) public pure returns (uint16); function getTutorialBabyGen(uint16 _dadGen) public pure returns (uint16); function getBreedingFee(uint40 _momId, uint40 _dadId) public pure returns (uint256); } /// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /// @title BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain. /// @author https://BlockChainArchitect.io /// @dev This is the main BlockchainCuties contract. For separated logical sections the code is divided in // several separately-instantiated sibling contracts that handle auctions and the genetic combination algorithm. // By keeping auctions separate it is possible to upgrade them without disrupting the main contract that tracks // the ownership of the cutie. The genetic combination algorithm is kept separate so that all of the rest of the // code can be open-sourced. // The contracts: // // - BlockchainCuties: The fundamental code, including main data storage, constants and data types, as well as // internal functions for managing these items ans ERC-721 implementation. // Various addresses and constraints for operations can be executed only by specific roles - // Owner, Operator and Parties. // Methods for interacting with additional features (Plugins). // The methods for breeding and keeping track of breeding offers, relies on external genetic combination // contract. // Public methods for auctioning or bidding or breeding. // // - SaleMarket and BreedingMarket: The actual auction functionality is handled in two sibling contracts - one // for sales and one for breeding. Auction creation and bidding is mostly mediated through this side of // the core contract. // // - Effects: Contracts allow to use item effects on cuties, implemented as plugins. Items are not stored in // blockchain to not overload Ethereum network. Operator generates signatures, and Plugins check it // and perform effect. // // - ItemMarket: Plugin contract used to transfer money from buyer to seller. // // - Bank: Plugin contract used to receive payments for payed features. contract BlockchainCutiesCore /*is ERC721, CutieCoreInterface*/ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name) { return "BlockchainCuties"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol) { return "BC"; } /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external pure returns (bool) { return interfaceID == 0x6466353c || interfaceID == bytes4(keccak256('supportsInterface(bytes4)')); } event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @dev The Birth event is fired as soon as a new cutie is created. This /// is any time a cutie comes into existence through the giveBirth method, as well as /// when a new gen0 cutie is created. event Birth(address indexed owner, uint40 cutieId, uint40 momId, uint40 dadId, uint256 genes); /// @dev This struct represents a blockchain Cutie. It was ensured that struct fits well into /// exactly two 256-bit words. The order of the members in this structure /// matters because of the Ethereum byte-packing rules. /// Reference: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Cutie { // The Cutie's genetic code is in these 256-bits. Cutie's genes never change. uint256 genes; // The timestamp from the block when this cutie was created. uint40 birthTime; // The minimum timestamp after which the cutie can start breeding // again. uint40 cooldownEndTime; // The cutie's parents ID is set to 0 for gen0 cuties. // Because of using 32-bit unsigned integers the limit is 4 billion cuties. // Current Ethereum annual limit is about 500 million transactions. uint40 momId; uint40 dadId; // Set the index in the cooldown array (see below) that means // the current cooldown duration for this Cutie. Starts at 0 // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding, regardless // of being cutie mom or cutie dad. uint16 cooldownIndex; // The "generation number" of the cutie. Cutioes minted by the contract // for sale are called "gen0" with generation number of 0. All other cuties' // generation number is the larger of their parents' two generation // numbers, plus one (i.e. max(mom.generation, dad.generation) + 1) uint16 generation; // Some optional data used by external contracts // Cutie struct is 2x256 bits long. uint64 optional; } /// @dev An array containing the Cutie struct for all Cuties in existence. The ID /// of each cutie is actually an index into this array. ID 0 is the parent /// of all generation 0 cats, and both parents to itself. It is an invalid genetic code. Cutie[] public cuties; /// @dev A mapping from cutie IDs to the address that owns them. All cuties have /// some valid owner address, even gen0 cuties are created with a non-zero owner. mapping (uint40 => address) public cutieIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from CutieIDs to an address that has been approved to call /// transferFrom(). A Cutie can have one approved address for transfer /// at any time. A zero value means that there is no outstanding approval. mapping (uint40 => address) public cutieIndexToApproved; /// @dev A mapping from CutieIDs to an address that has been approved to use /// this Cutie for breeding via breedWith(). A Cutie can have one approved /// address for breeding at any time. A zero value means that there is no outstanding approval. mapping (uint40 => address) public sireAllowedToAddress; /// @dev The address of the Market contract used to sell cuties. This /// contract used both peer-to-peer sales and the gen0 sales that are /// initiated each 15 minutes. MarketInterface public saleMarket; /// @dev The address of a custom Market subclassed contract used for breeding /// auctions. Is to be separated from saleMarket as the actions taken on success /// after a sales and breeding auction are quite different. MarketInterface public breedingMarket; // Modifiers to check that inputs can be safely stored with a certain // number of bits. modifier canBeStoredIn40Bits(uint256 _value) { require(_value <= 0xFFFFFFFFFF); _; } /// @notice Returns the total number of Cuties in existence. /// @dev Required for ERC-721 compliance. function totalSupply() external view returns (uint256) { return cuties.length - 1; } /// @notice Returns the total number of Cuties in existence. /// @dev Required for ERC-721 compliance. function _totalSupply() internal view returns (uint256) { return cuties.length - 1; } // Internal utility functions assume that their input arguments // are valid. Public methods sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a certain Cutie. /// @param _claimant the address we are validating against. /// @param _cutieId cutie id, only valid when > 0 function _isOwner(address _claimant, uint40 _cutieId) internal view returns (bool) { return cutieIndexToOwner[_cutieId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a certain Cutie. /// @param _claimant the address we are confirming the cutie is approved for. /// @param _cutieId cutie id, only valid when > 0 function _approvedFor(address _claimant, uint40 _cutieId) internal view returns (bool) { return cutieIndexToApproved[_cutieId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is done on purpose: /// _approve() and transferFrom() are used together for putting Cuties on auction. /// There is no value in spamming the log with Approval events in that case. function _approve(uint40 _cutieId, address _approved) internal { cutieIndexToApproved[_cutieId] = _approved; } /// @notice Returns the number of Cuties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) external view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Cutie to another address. When transferring to a smart /// contract, ensure that it is aware of ERC-721 (or /// BlockchainCuties specifically), otherwise the Cutie may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _cutieId The ID of the Cutie to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _cutieId) external whenNotPaused canBeStoredIn40Bits(_cutieId) { // You can only send your own cutie. require(_isOwner(msg.sender, uint40(_cutieId))); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, uint40(_cutieId)); } /// @notice Grant another address the right to transfer a perticular Cutie via transferFrom(). /// This flow is preferred for transferring NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to clear all approvals. /// @param _cutieId The ID of the Cutie that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _cutieId) external whenNotPaused canBeStoredIn40Bits(_cutieId) { // Only cutie's owner can grant transfer approval. require(_isOwner(msg.sender, uint40(_cutieId))); // Registering approval replaces any previous approval. _approve(uint40(_cutieId), _to); // Emit approval event. emit Approval(msg.sender, _to, _cutieId); } /// @notice Transfers the ownership of an NFT from one address to another address. /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external whenNotPaused canBeStoredIn40Bits(_tokenId) { require(_to != address(0)); require(_to != address(this)); require(_to != address(saleMarket)); require(_to != address(breedingMarket)); // Check for approval and valid ownership require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender)); require(_isOwner(_from, uint40(_tokenId))); // Reassign ownership, clearing pending approvals and emitting Transfer event. _transfer(_from, _to, uint40(_tokenId)); ERC721TokenReceiver (_to).onERC721Received(_from, _tokenId, data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "" /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused canBeStoredIn40Bits(_tokenId) { require(_to != address(0)); require(_to != address(this)); require(_to != address(saleMarket)); require(_to != address(breedingMarket)); // Check for approval and valid ownership require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender)); require(_isOwner(_from, uint40(_tokenId))); // Reassign ownership, clearing pending approvals and emitting Transfer event. _transfer(_from, _to, uint40(_tokenId)); } /// @notice Transfer a Cutie owned by another address, for which the calling address /// has been granted transfer approval by the owner. /// @param _from The address that owns the Cutie to be transfered. /// @param _to Any address, including the caller address, can take ownership of the Cutie. /// @param _tokenId The ID of the Cutie to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused canBeStoredIn40Bits(_tokenId) { // Check for approval and valid ownership require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender)); require(_isOwner(_from, uint40(_tokenId))); // Reassign ownership, clearing pending approvals and emitting Transfer event. _transfer(_from, _to, uint40(_tokenId)); } /// @notice Returns the address currently assigned ownership of a given Cutie. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _cutieId) external view canBeStoredIn40Bits(_cutieId) returns (address owner) { owner = cutieIndexToOwner[uint40(_cutieId)]; require(owner != address(0)); } /// @notice Returns the nth Cutie assigned to an address, with n specified by the /// _index argument. /// @param _owner The owner of the Cuties we are interested in. /// @param _index The zero-based index of the cutie within the owner's list of cuties. /// Must be less than balanceOf(_owner). /// @dev This method must not be called by smart contract code. It will almost /// certainly blow past the block gas limit once there are a large number of /// Cuties in existence. Exists only to allow off-chain queries of ownership. /// Optional method for ERC-721. function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 cutieId) { uint40 count = 0; for (uint40 i = 1; i <= _totalSupply(); ++i) { if (cutieIndexToOwner[i] == _owner) { if (count == _index) { return i; } else { count++; } } } revert(); } /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external pure returns (uint256) { return _index; } /// @dev A mapping from Cuties owner (account) to an address that has been approved to call /// transferFrom() for all cuties, owned by owner. /// Only one approved address is permitted for each account for transfer /// at any time. A zero value means there is no outstanding approval. mapping (address => address) public addressToApprovedAll; /// @notice Enable or disable approval for a third party ("operator") to manage /// all your asset. /// @dev Emits the ApprovalForAll event /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { if (_approved) { addressToApprovedAll[msg.sender] = _operator; } else { delete addressToApprovedAll[msg.sender]; } emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view canBeStoredIn40Bits(_tokenId) returns (address) { require(_tokenId <= _totalSupply()); if (cutieIndexToApproved[uint40(_tokenId)] != address(0)) { return cutieIndexToApproved[uint40(_tokenId)]; } address owner = cutieIndexToOwner[uint40(_tokenId)]; return addressToApprovedAll[owner]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return addressToApprovedAll[_owner] == _operator; } function _isApprovedForAll(address _owner, address _operator) internal view returns (bool) { return addressToApprovedAll[_owner] == _operator; } ConfigInterface public config; /// @dev Update the address of the config contract. /// @param _address An address of a ConfigInterface contract instance to be used from this point forward. function setConfigAddress(address _address) public onlyOwner { ConfigInterface candidateContract = ConfigInterface(_address); require(candidateContract.isConfig()); // Set the new contract address config = candidateContract; } function getCooldownIndexFromGeneration(uint16 _generation) internal view returns (uint16) { return config.getCooldownIndexFromGeneration(_generation); } /// @dev An internal method that creates a new cutie and stores it. This /// method does not check anything and should only be called when the /// input data is valid for sure. Will generate both a Birth event /// and a Transfer event. /// @param _momId The cutie ID of the mom of this cutie (zero for gen0) /// @param _dadId The cutie ID of the dad of this cutie (zero for gen0) /// @param _generation The generation number of this cutie, must be computed by caller. /// @param _genes The cutie's genetic code. /// @param _owner The initial owner of this cutie, must be non-zero (except for the unCutie, ID 0) function _createCutie( uint40 _momId, uint40 _dadId, uint16 _generation, uint16 _cooldownIndex, uint256 _genes, address _owner, uint40 _birthTime ) internal returns (uint40) { Cutie memory _cutie = Cutie({ genes: _genes, birthTime: _birthTime, cooldownEndTime: 0, momId: _momId, dadId: _dadId, cooldownIndex: _cooldownIndex, generation: _generation, optional: 0 }); uint256 newCutieId256 = cuties.push(_cutie) - 1; // Check if id can fit into 40 bits require(newCutieId256 <= 0xFFFFFFFFFF); uint40 newCutieId = uint40(newCutieId256); // emit the birth event emit Birth(_owner, newCutieId, _cutie.momId, _cutie.dadId, _cutie.genes); // This will assign ownership, as well as emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newCutieId); return newCutieId; } /// @notice Returns all the relevant information about a certain cutie. /// @param _id The ID of the cutie of interest. function getCutie(uint40 _id) external view returns ( uint256 genes, uint40 birthTime, uint40 cooldownEndTime, uint40 momId, uint40 dadId, uint16 cooldownIndex, uint16 generation ) { Cutie storage cutie = cuties[_id]; genes = cutie.genes; birthTime = cutie.birthTime; cooldownEndTime = cutie.cooldownEndTime; momId = cutie.momId; dadId = cutie.dadId; cooldownIndex = cutie.cooldownIndex; generation = cutie.generation; } /// @dev Assigns ownership of a particular Cutie to an address. function _transfer(address _from, address _to, uint40 _cutieId) internal { // since the number of cuties is capped to 2^40 // there is no way to overflow this ownershipTokenCount[_to]++; // transfer ownership cutieIndexToOwner[_cutieId] = _to; // When creating new cuties _from is 0x0, but we cannot account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the cutie is transferred also clear breeding allowances delete sireAllowedToAddress[_cutieId]; // clear any previously approved ownership exchange delete cutieIndexToApproved[_cutieId]; } // Emit the transfer event. emit Transfer(_from, _to, _cutieId); } /// @dev For transferring a cutie owned by this contract to the specified address. /// Used to rescue lost cuties. (There is no "proper" flow where this contract /// should be the owner of any Cutie. This function exists for us to reassign /// the ownership of Cuties that users may have accidentally sent to our address.) /// @param _cutieId - ID of cutie /// @param _recipient - Address to send the cutie to function restoreCutieToAddress(uint40 _cutieId, address _recipient) public onlyOperator whenNotPaused { require(_isOwner(this, _cutieId)); _transfer(this, _recipient, _cutieId); } address ownerAddress; address operatorAddress; bool public paused = false; modifier onlyOwner() { require(msg.sender == ownerAddress); _; } function setOwner(address _newOwner) public onlyOwner { require(_newOwner != address(0)); ownerAddress = _newOwner; } modifier onlyOperator() { require(msg.sender == operatorAddress || msg.sender == ownerAddress); _; } function setOperator(address _newOperator) public onlyOwner { require(_newOperator != address(0)); operatorAddress = _newOperator; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() public onlyOwner whenNotPaused { paused = true; } string public metadataUrlPrefix = "https://blockchaincuties.co/cutie/"; string public metadataUrlSuffix = ".svg"; /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string infoUrl) { return concat(toSlice(metadataUrlPrefix), toSlice(concat(toSlice(uintToString(_tokenId)), toSlice(metadataUrlSuffix)))); } function setMetadataUrl(string _metadataUrlPrefix, string _metadataUrlSuffix) public onlyOwner { metadataUrlPrefix = _metadataUrlPrefix; metadataUrlSuffix = _metadataUrlSuffix; } mapping(address => PluginInterface) public plugins; PluginInterface[] public pluginsArray; mapping(uint40 => address) public usedSignes; uint40 public minSignId; event GenesChanged(uint40 indexed cutieId, uint256 oldValue, uint256 newValue); event CooldownEndTimeChanged(uint40 indexed cutieId, uint40 oldValue, uint40 newValue); event CooldownIndexChanged(uint40 indexed cutieId, uint16 ololdValue, uint16 newValue); event GenerationChanged(uint40 indexed cutieId, uint16 oldValue, uint16 newValue); event OptionalChanged(uint40 indexed cutieId, uint64 oldValue, uint64 newValue); event SignUsed(uint40 signId, address sender); event MinSignSet(uint40 signId); /// @dev Sets the reference to the plugin contract. /// @param _address - Address of plugin contract. function addPlugin(address _address) public onlyOwner { PluginInterface candidateContract = PluginInterface(_address); // verify that a contract is what we expect require(candidateContract.isPluginInterface()); // Set the new contract address plugins[_address] = candidateContract; pluginsArray.push(candidateContract); } /// @dev Remove plugin and calls onRemove to cleanup function removePlugin(address _address) public onlyOwner { plugins[_address].onRemove(); delete plugins[_address]; uint256 kindex = 0; while (kindex < pluginsArray.length) { if (address(pluginsArray[kindex]) == _address) { pluginsArray[kindex] = pluginsArray[pluginsArray.length-1]; pluginsArray.length--; } else { kindex++; } } } /// @dev Put a cutie up for plugin feature. function runPlugin( address _pluginAddress, uint40 _cutieId, uint256 _parameter ) public whenNotPaused payable { // If cutie is already on any auction or in adventure, this will throw // because it will be owned by the other contract. // If _cutieId is 0, then cutie is not used on this feature. require(_cutieId == 0 || _isOwner(msg.sender, _cutieId)); require(address(plugins[_pluginAddress]) != address(0)); if (_cutieId > 0) { _approve(_cutieId, _pluginAddress); } // Plugin contract throws if inputs are invalid and clears // transfer after escrowing the cutie. plugins[_pluginAddress].run.value(msg.value)( _cutieId, _parameter, msg.sender ); } /// @dev Called from plugin contract when using items as effect function getGenes(uint40 _id) public view returns ( uint256 genes ) { Cutie storage cutie = cuties[_id]; genes = cutie.genes; } /// @dev Called from plugin contract when using items as effect function changeGenes( uint40 _cutieId, uint256 _genes) public whenNotPaused { // if caller is registered plugin contract require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.genes != _genes) { emit GenesChanged(_cutieId, cutie.genes, _genes); cutie.genes = _genes; } } function getCooldownEndTime(uint40 _id) public view returns ( uint40 cooldownEndTime ) { Cutie storage cutie = cuties[_id]; cooldownEndTime = cutie.cooldownEndTime; } function changeCooldownEndTime( uint40 _cutieId, uint40 _cooldownEndTime) public whenNotPaused { require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.cooldownEndTime != _cooldownEndTime) { emit CooldownEndTimeChanged(_cutieId, cutie.cooldownEndTime, _cooldownEndTime); cutie.cooldownEndTime = _cooldownEndTime; } } function getCooldownIndex(uint40 _id) public view returns ( uint16 cooldownIndex ) { Cutie storage cutie = cuties[_id]; cooldownIndex = cutie.cooldownIndex; } function changeCooldownIndex( uint40 _cutieId, uint16 _cooldownIndex) public whenNotPaused { require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.cooldownIndex != _cooldownIndex) { emit CooldownIndexChanged(_cutieId, cutie.cooldownIndex, _cooldownIndex); cutie.cooldownIndex = _cooldownIndex; } } function changeGeneration( uint40 _cutieId, uint16 _generation) public whenNotPaused { require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.generation != _generation) { emit GenerationChanged(_cutieId, cutie.generation, _generation); cutie.generation = _generation; } } function getGeneration(uint40 _id) public view returns (uint16 generation) { Cutie storage cutie = cuties[_id]; generation = cutie.generation; } function changeOptional( uint40 _cutieId, uint64 _optional) public whenNotPaused { require(address(plugins[msg.sender]) != address(0)); Cutie storage cutie = cuties[_cutieId]; if (cutie.optional != _optional) { emit OptionalChanged(_cutieId, cutie.optional, _optional); cutie.optional = _optional; } } function getOptional(uint40 _id) public view returns (uint64 optional) { Cutie storage cutie = cuties[_id]; optional = cutie.optional; } /// @dev Common function to be used also in backend function hashArguments( address _pluginAddress, uint40 _signId, uint40 _cutieId, uint128 _value, uint256 _parameter) public pure returns (bytes32 msgHash) { msgHash = keccak256(_pluginAddress, _signId, _cutieId, _value, _parameter); } /// @dev Common function to be used also in backend function getSigner( address _pluginAddress, uint40 _signId, uint40 _cutieId, uint128 _value, uint256 _parameter, uint8 _v, bytes32 _r, bytes32 _s ) public pure returns (address) { bytes32 msgHash = hashArguments(_pluginAddress, _signId, _cutieId, _value, _parameter); return ecrecover(msgHash, _v, _r, _s); } /// @dev Common function to be used also in backend function isValidSignature( address _pluginAddress, uint40 _signId, uint40 _cutieId, uint128 _value, uint256 _parameter, uint8 _v, bytes32 _r, bytes32 _s ) public view returns (bool) { return getSigner(_pluginAddress, _signId, _cutieId, _value, _parameter, _v, _r, _s) == operatorAddress; } /// @dev Put a cutie up for plugin feature with signature. /// Can be used for items equip, item sales and other features. /// Signatures are generated by Operator role. function runPluginSigned( address _pluginAddress, uint40 _signId, uint40 _cutieId, uint128 _value, uint256 _parameter, uint8 _v, bytes32 _r, bytes32 _s ) public whenNotPaused payable { // If cutie is already on any auction or in adventure, this will throw // as it will be owned by the other contract. // If _cutieId is 0, then cutie is not used on this feature. require(_cutieId == 0 || _isOwner(msg.sender, _cutieId)); require(address(plugins[_pluginAddress]) != address(0)); require (usedSignes[_signId] == address(0)); require (_signId >= minSignId); // value can also be zero for free calls require (_value <= msg.value); require (isValidSignature(_pluginAddress, _signId, _cutieId, _value, _parameter, _v, _r, _s)); usedSignes[_signId] = msg.sender; emit SignUsed(_signId, msg.sender); // Plugin contract throws if inputs are invalid and clears // transfer after escrowing the cutie. plugins[_pluginAddress].runSigned.value(_value)( _cutieId, _parameter, msg.sender ); } /// @dev Sets minimal signId, than can be used. /// All unused signatures less than signId will be cancelled on off-chain server /// and unused items will be transfered back to owner. function setMinSign(uint40 _newMinSignId) public onlyOperator { require (_newMinSignId > minSignId); minSignId = _newMinSignId; emit MinSignSet(minSignId); } event BreedingApproval(address indexed _owner, address indexed _approved, uint256 _tokenId); // Set in case the core contract is broken and an upgrade is required address public upgradedContractAddress; function isCutieCore() pure public returns (bool) { return true; } /// @notice Creates the main BlockchainCuties smart contract instance. function BlockchainCutiesCore() public { // Starts paused. paused = true; // the creator of the contract is the initial owner ownerAddress = msg.sender; // the creator of the contract is also the initial operator operatorAddress = msg.sender; // start with the mythical cutie 0 - so there are no generation-0 parent issues _createCutie(0, 0, 0, 0, uint256(-1), address(0), 0); } event ContractUpgrade(address newContract); /// @dev Aimed to mark the smart contract as upgraded if there is a crucial /// bug. This keeps track of the new contract and indicates that the new address is set. /// Updating to the new contract address is up to the clients. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _newAddress new address function setUpgradedAddress(address _newAddress) public onlyOwner whenPaused { require(_newAddress != address(0)); upgradedContractAddress = _newAddress; emit ContractUpgrade(upgradedContractAddress); } /// @dev Import cuties from previous version of Core contract. /// @param _oldAddress Old core contract address /// @param _fromIndex (inclusive) /// @param _toIndex (inclusive) function migrate(address _oldAddress, uint40 _fromIndex, uint40 _toIndex) public onlyOwner whenPaused { require(_totalSupply() + 1 == _fromIndex); BlockchainCutiesCore old = BlockchainCutiesCore(_oldAddress); for (uint40 i = _fromIndex; i <= _toIndex; i++) { uint256 genes; uint40 birthTime; uint40 cooldownEndTime; uint40 momId; uint40 dadId; uint16 cooldownIndex; uint16 generation; (genes, birthTime, cooldownEndTime, momId, dadId, cooldownIndex, generation) = old.getCutie(i); Cutie memory _cutie = Cutie({ genes: genes, birthTime: birthTime, cooldownEndTime: cooldownEndTime, momId: momId, dadId: dadId, cooldownIndex: cooldownIndex, generation: generation, optional: 0 }); cuties.push(_cutie); } } /// @dev Import cuties from previous version of Core contract (part 2). /// @param _oldAddress Old core contract address /// @param _fromIndex (inclusive) /// @param _toIndex (inclusive) function migrate2(address _oldAddress, uint40 _fromIndex, uint40 _toIndex, address saleAddress, address breedingAddress) public onlyOwner whenPaused { BlockchainCutiesCore old = BlockchainCutiesCore(_oldAddress); MarketInterface oldSaleMarket = MarketInterface(saleAddress); MarketInterface oldBreedingMarket = MarketInterface(breedingAddress); for (uint40 i = _fromIndex; i <= _toIndex; i++) { address owner = old.ownerOf(i); if (owner == saleAddress) { (owner,,,,,) = oldSaleMarket.getAuctionInfo(i); } if (owner == breedingAddress) { (owner,,,,,) = oldBreedingMarket.getAuctionInfo(i); } _transfer(0, owner, i); } } /// @dev Override unpause so it requires upgradedContractAddress not set, because then the contract was upgraded. function unpause() public onlyOwner whenPaused { require(upgradedContractAddress == address(0)); paused = false; } // Counts the number of cuties the contract owner has created. uint40 public promoCutieCreatedCount; uint40 public gen0CutieCreatedCount; uint40 public gen0Limit = 50000; uint40 public promoLimit = 5000; /// @dev Creates a new gen0 cutie with the given genes and /// creates an auction for it. function createGen0Auction(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration) public onlyOperator { require(gen0CutieCreatedCount < gen0Limit); uint40 cutieId = _createCutie(0, 0, 0, 0, _genes, address(this), uint40(now)); _approve(cutieId, saleMarket); saleMarket.createAuction( cutieId, startPrice, endPrice, duration, address(this) ); gen0CutieCreatedCount++; } function createPromoCutie(uint256 _genes, address _owner) public onlyOperator { require(promoCutieCreatedCount < promoLimit); if (_owner == address(0)) { _owner = operatorAddress; } promoCutieCreatedCount++; gen0CutieCreatedCount++; _createCutie(0, 0, 0, 0, _genes, _owner, uint40(now)); } /// @dev Put a cutie up for auction to be dad. /// Performs checks to ensure the cutie can be dad, then /// delegates to reverse auction. /// Optional money amount can be sent to contract to feature auction. /// Pricea are available on web. function createBreedingAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration ) public whenNotPaused payable { // Auction contract checks input sizes // If cutie is already on any auction, this will throw // because it will be owned by the auction contract. require(_isOwner(msg.sender, _cutieId)); require(canBreed(_cutieId)); _approve(_cutieId, breedingMarket); // breeding auction function is called if inputs are invalid and clears // transfer and sire approval after escrowing the cutie. breedingMarket.createAuction.value(msg.value)( _cutieId, _startPrice, _endPrice, _duration, msg.sender ); } /// @dev Sets the reference to the breeding auction. /// @param _breedingAddress - Address of breeding market contract. /// @param _saleAddress - Address of sale market contract. function setMarketAddress(address _breedingAddress, address _saleAddress) public onlyOwner { //require(address(breedingMarket) == address(0)); //require(address(saleMarket) == address(0)); breedingMarket = MarketInterface(_breedingAddress); saleMarket = MarketInterface(_saleAddress); } /// @dev Completes a breeding auction by bidding. /// Immediately breeds the winning mom with the dad on auction. /// @param _dadId - ID of the dad on auction. /// @param _momId - ID of the mom owned by the bidder. function bidOnBreedingAuction( uint40 _dadId, uint40 _momId ) public payable whenNotPaused returns (uint256) { // Auction contract checks input sizes require(_isOwner(msg.sender, _momId)); require(canBreed(_momId)); require(_canMateViaMarketplace(_momId, _dadId)); // Take breeding fee uint256 fee = getBreedingFee(_momId, _dadId); require(msg.value >= fee); // breeding auction will throw if the bid fails. breedingMarket.bid.value(msg.value - fee)(_dadId); return _breedWith(_momId, _dadId); } /// @dev Put a cutie up for auction. /// Does some ownership trickery for creating auctions in one transaction. /// Optional money amount can be sent to contract to feature auction. /// Pricea are available on web. function createSaleAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration ) public whenNotPaused payable { // Auction contract checks input sizes // If cutie is already on any auction, this will throw // because it will be owned by the auction contract. require(_isOwner(msg.sender, _cutieId)); _approve(_cutieId, saleMarket); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the cutie. saleMarket.createAuction.value(msg.value)( _cutieId, _startPrice, _endPrice, _duration, msg.sender ); } /// @dev The address of the sibling contract that is used to implement the genetic combination algorithm. GeneMixerInterface geneMixer; /// @dev Check if dad has authorized breeding with the mom. True if both dad /// and mom have the same owner, or if the dad has given breeding permission to /// the mom's owner (via approveBreeding()). function _isBreedingPermitted(uint40 _dadId, uint40 _momId) internal view returns (bool) { address momOwner = cutieIndexToOwner[_momId]; address dadOwner = cutieIndexToOwner[_dadId]; // Breeding is approved if they have same owner, or if the mom's owner was given // permission to breed with the dad. return (momOwner == dadOwner || sireAllowedToAddress[_dadId] == momOwner); } /// @dev Update the address of the genetic contract. /// @param _address An address of a GeneMixer contract instance to be used from this point forward. function setGeneMixerAddress(address _address) public onlyOwner { GeneMixerInterface candidateContract = GeneMixerInterface(_address); require(candidateContract.isGeneMixer()); // Set the new contract address geneMixer = candidateContract; } /// @dev Checks that a given cutie is able to breed. Requires that the /// current cooldown is finished (for dads) function _canBreed(Cutie _cutie) internal view returns (bool) { return _cutie.cooldownEndTime <= now; } /// @notice Grants approval to another user to sire with one of your Cuties. /// @param _addr The address that will be able to sire with your Cutie. Set to /// address(0) to clear all breeding approvals for this Cutie. /// @param _dadId A Cutie that you own that _addr will now be able to dad with. function approveBreeding(address _addr, uint40 _dadId) public whenNotPaused { require(_isOwner(msg.sender, _dadId)); sireAllowedToAddress[_dadId] = _addr; emit BreedingApproval(msg.sender, _addr, _dadId); } /// @dev Set the cooldownEndTime for the given Cutie, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _cutie A reference to the Cutie in storage which needs its timer started. function _triggerCooldown(uint40 _cutieId, Cutie storage _cutie) internal { // Compute the end of the cooldown time, based on current cooldownIndex uint40 oldValue = _cutie.cooldownIndex; _cutie.cooldownEndTime = config.getCooldownEndTimeFromIndex(_cutie.cooldownIndex); emit CooldownEndTimeChanged(_cutieId, oldValue, _cutie.cooldownEndTime); // Increment the breeding count. if (_cutie.cooldownIndex + 1 < config.getCooldownIndexCount()) { uint16 oldValue2 = _cutie.cooldownIndex; _cutie.cooldownIndex++; emit CooldownIndexChanged(_cutieId, oldValue2, _cutie.cooldownIndex); } } /// @notice Checks that a certain cutie is not /// in the middle of a breeding cooldown and is able to breed. /// @param _cutieId reference the id of the cutie, any user can inquire about it function canBreed(uint40 _cutieId) public view returns (bool) { require(_cutieId > 0); Cutie storage cutie = cuties[_cutieId]; return _canBreed(cutie); } /// @dev Check if given mom and dad are a valid mating pair. function _canPairMate( Cutie storage _mom, uint40 _momId, Cutie storage _dad, uint40 _dadId ) private view returns(bool) { // A Cutie can't breed with itself. if (_dadId == _momId) { return false; } // Cuties can't breed with their parents. if (_mom.momId == _dadId) { return false; } if (_mom.dadId == _dadId) { return false; } if (_dad.momId == _momId) { return false; } if (_dad.dadId == _momId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a mom ID of zero). if (_dad.momId == 0) { return true; } if (_mom.momId == 0) { return true; } // Cuties can't breed with full or half siblings. if (_dad.momId == _mom.momId) { return false; } if (_dad.momId == _mom.dadId) { return false; } if (_dad.dadId == _mom.momId) { return false; } if (_dad.dadId == _mom.dadId) { return false; } if (geneMixer.canBreed(_momId, _mom.genes, _dadId, _dad.genes)) { return true; } return false; } /// @notice Checks to see if two cuties can breed together (checks both /// ownership and breeding approvals, but does not check if both cuties are ready for /// breeding). /// @param _momId The ID of the proposed mom. /// @param _dadId The ID of the proposed dad. function canBreedWith(uint40 _momId, uint40 _dadId) public view returns(bool) { require(_momId > 0); require(_dadId > 0); Cutie storage mom = cuties[_momId]; Cutie storage dad = cuties[_dadId]; return _canPairMate(mom, _momId, dad, _dadId) && _isBreedingPermitted(_dadId, _momId); } /// @dev Internal check to see if a given dad and mom are a valid mating pair for /// breeding via market (this method doesn't check ownership and if mating is allowed). function _canMateViaMarketplace(uint40 _momId, uint40 _dadId) internal view returns (bool) { Cutie storage mom = cuties[_momId]; Cutie storage dad = cuties[_dadId]; return _canPairMate(mom, _momId, dad, _dadId); } function getBreedingFee(uint40 _momId, uint40 _dadId) public view returns (uint256) { return config.getBreedingFee(_momId, _dadId); } /// @notice Breed cuties that you own, or for which you /// have previously been given Breeding approval. Will either make your cutie give birth, or will /// fail. /// @param _momId The ID of the Cutie acting as mom (will end up give birth if successful) /// @param _dadId The ID of the Cutie acting as dad (will begin its breeding cooldown if successful) function breedWith(uint40 _momId, uint40 _dadId) public whenNotPaused payable returns (uint40) { // Caller must own the mom. require(_isOwner(msg.sender, _momId)); // Neither dad nor mom can be on auction during // breeding. // For mom: The caller of this function can't be the owner of the mom // because the owner of a Cutie on auction is the auction house, and the // auction house will never call breedWith(). // For dad: Similarly, a dad on auction will be owned by the auction house // and the act of transferring ownership will have cleared any outstanding // breeding approval. // Thus we don't need check if either cutie // is on auction. // Check that mom and dad are both owned by caller, or that the dad // has given breeding permission to caller (i.e. mom's owner). // Will fail for _dadId = 0 require(_isBreedingPermitted(_dadId, _momId)); // Check breeding fee require(getBreedingFee(_momId, _dadId) <= msg.value); // Grab a reference to the potential mom Cutie storage mom = cuties[_momId]; // Make sure mom's cooldown isn't active, or in the middle of a breeding cooldown require(_canBreed(mom)); // Grab a reference to the potential dad Cutie storage dad = cuties[_dadId]; // Make sure dad cooldown isn't active, or in the middle of a breeding cooldown require(_canBreed(dad)); // Test that these cuties are a valid mating pair. require(_canPairMate( mom, _momId, dad, _dadId )); return _breedWith(_momId, _dadId); } /// @dev Internal utility function to start breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint40 _momId, uint40 _dadId) internal returns (uint40) { // Grab a reference to the Cuties from storage. Cutie storage dad = cuties[_dadId]; Cutie storage mom = cuties[_momId]; // Trigger the cooldown for both parents. _triggerCooldown(_dadId, dad); _triggerCooldown(_momId, mom); // Clear breeding permission for both parents. delete sireAllowedToAddress[_momId]; delete sireAllowedToAddress[_dadId]; // Check that the mom is a valid cutie. require(mom.birthTime != 0); // Determine the higher generation number of the two parents uint16 babyGen = config.getBabyGen(mom.generation, dad.generation); // Call the gene mixing operation. uint256 childGenes = geneMixer.mixGenes(mom.genes, dad.genes); // Make the new cutie address owner = cutieIndexToOwner[_momId]; uint40 cutieId = _createCutie(_momId, _dadId, babyGen, getCooldownIndexFromGeneration(babyGen), childGenes, owner, mom.cooldownEndTime); // return the new cutie's ID return cutieId; } mapping(address => uint40) isTutorialPetUsed; /// @dev Completes a breeding tutorial cutie (non existing in blockchain) /// with auction by bidding. Immediately breeds with dad on auction. /// @param _dadId - ID of the dad on auction. function bidOnBreedingAuctionTutorial( uint40 _dadId ) public payable whenNotPaused returns (uint) { require(isTutorialPetUsed[msg.sender] == 0); // Take breeding fee uint256 fee = getBreedingFee(0, _dadId); require(msg.value >= fee); // breeding auction will throw if the bid fails. breedingMarket.bid.value(msg.value - fee)(_dadId); // Grab a reference to the Cuties from storage. Cutie storage dad = cuties[_dadId]; // Trigger the cooldown for parent. _triggerCooldown(_dadId, dad); // Clear breeding permission for parent. delete sireAllowedToAddress[_dadId]; uint16 babyGen = config.getTutorialBabyGen(dad.generation); // tutorial pet genome is zero uint256 childGenes = geneMixer.mixGenes(0x0, dad.genes); // tutorial pet id is zero uint40 cutieId = _createCutie(0, _dadId, babyGen, getCooldownIndexFromGeneration(babyGen), childGenes, msg.sender, 12); isTutorialPetUsed[msg.sender] = cutieId; // return the new cutie's ID return cutieId; } address party1address; address party2address; address party3address; address party4address; address party5address; /// @dev Setup project owners function setParties(address _party1, address _party2, address _party3, address _party4, address _party5) public onlyOwner { require(_party1 != address(0)); require(_party2 != address(0)); require(_party3 != address(0)); require(_party4 != address(0)); require(_party5 != address(0)); party1address = _party1; party2address = _party2; party3address = _party3; party4address = _party4; party5address = _party5; } /// @dev Reject all Ether which is not from game contracts from being sent here. function() external payable { require( msg.sender == address(saleMarket) || msg.sender == address(breedingMarket) || address(plugins[msg.sender]) != address(0) ); } /// @dev The balance transfer from the market and plugins contract /// to the CutieCore contract. function withdrawBalances() external { require( msg.sender == ownerAddress || msg.sender == operatorAddress); saleMarket.withdrawEthFromBalance(); breedingMarket.withdrawEthFromBalance(); for (uint32 i = 0; i < pluginsArray.length; ++i) { pluginsArray[i].withdraw(); } } /// @dev The balance transfer from CutieCore contract to project owners function withdrawEthFromBalance() external { require( msg.sender == party1address || msg.sender == party2address || msg.sender == party3address || msg.sender == party4address || msg.sender == party5address || msg.sender == ownerAddress || msg.sender == operatorAddress); require(party1address != 0); require(party2address != 0); require(party3address != 0); require(party4address != 0); require(party5address != 0); uint256 total = address(this).balance; party1address.transfer(total*105/1000); party2address.transfer(total*105/1000); party3address.transfer(total*140/1000); party4address.transfer(total*140/1000); party5address.transfer(total*510/1000); } /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ struct slice { uint _len; uint _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal pure returns (string) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } function uintToString(uint256 a) internal pure returns (string result) { string memory r = ""; do { uint b = a % 10; a /= 10; string memory c = ""; if (b == 0) c = "0"; else if (b == 1) c = "1"; else if (b == 2) c = "2"; else if (b == 3) c = "3"; else if (b == 4) c = "4"; else if (b == 5) c = "5"; else if (b == 6) c = "6"; else if (b == 7) c = "7"; else if (b == 8) c = "8"; else if (b == 9) c = "9"; r = concat(toSlice(c), toSlice(r)); } while (a > 0); result = r; } }
@dev Creates a new gen0 cutie with the given genes and creates an auction for it.
function createGen0Auction(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration) public onlyOperator { require(gen0CutieCreatedCount < gen0Limit); uint40 cutieId = _createCutie(0, 0, 0, 0, _genes, address(this), uint40(now)); _approve(cutieId, saleMarket); saleMarket.createAuction( cutieId, startPrice, endPrice, duration, address(this) ); gen0CutieCreatedCount++; }
12,941,819
[ 1, 2729, 279, 394, 3157, 20, 6391, 1385, 598, 326, 864, 11423, 471, 225, 3414, 392, 279, 4062, 364, 518, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 7642, 20, 37, 4062, 12, 11890, 5034, 389, 18036, 16, 2254, 10392, 787, 5147, 16, 2254, 10392, 679, 5147, 16, 2254, 7132, 3734, 13, 1071, 1338, 5592, 203, 565, 288, 203, 3639, 2583, 12, 4507, 20, 15812, 1385, 6119, 1380, 411, 3157, 20, 3039, 1769, 203, 3639, 2254, 7132, 6391, 1385, 548, 273, 389, 2640, 15812, 1385, 12, 20, 16, 374, 16, 374, 16, 374, 16, 389, 18036, 16, 1758, 12, 2211, 3631, 2254, 7132, 12, 3338, 10019, 203, 3639, 389, 12908, 537, 12, 5150, 1385, 548, 16, 272, 5349, 3882, 278, 1769, 203, 203, 3639, 272, 5349, 3882, 278, 18, 2640, 37, 4062, 12, 203, 5411, 6391, 1385, 548, 16, 203, 5411, 787, 5147, 16, 203, 5411, 679, 5147, 16, 203, 5411, 3734, 16, 203, 5411, 1758, 12, 2211, 13, 203, 3639, 11272, 203, 203, 3639, 3157, 20, 15812, 1385, 6119, 1380, 9904, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title The `Snapper` contract. * @notice The data storage part of the whole `Snapper` app. * @dev Logics like generating snapshot image / delta file and calling `takeSnapshot` are handled by the Lambda part. * @dev `latestSnapshotInfo` is the only method clients should care about. */ contract Snapper is Ownable { /** * @notice Initialize intialized regions. * @param regionId The id of region which have its own snapshot. */ error CannotBeReInitialized(uint256 regionId); /** * @notice `lastSnapshotBlock_` value is invaild. * @dev `lastSnapshotBlock_` must be equal to the region latest snapshot block. * @param regionId The region snapshotted on. * @param last The wrong `lastSnapshotBlock_` value. * @param latest The value `lastSnapshotBlock_` should be. */ error InvalidLastSnapshotBlock(uint256 regionId, uint256 last, uint256 latest); /** * @notice `targetSnapshotBlock_` value is invaild. * @dev `targetSnapshotBlock_` must be greater than region latest snapshot block. * @param regionId The region snapshotted on. * @param target The wrong `targetSnapshotBlock_` value. * @param latest The value `targetSnapshotBlock_` should greater than. */ error InvalidTargetSnapshotBlock(uint256 regionId, uint256 target, uint256 latest); /** * @notice New snapshot is taken. * @dev For more information see https://gist.github.com/zxygentoo/6575a49ff89831cdd71598d49527278b * @param regionId The map region snapshotted on. * @param block The block number snapshotted for The Space. * @param cid IPFS CID of the snapshot file. */ event Snapshot(uint256 indexed regionId, uint256 indexed block, string cid); /** * @notice New delta is generated. * @dev For more information see https://gist.github.com/zxygentoo/6575a49ff89831cdd71598d49527278b * @param regionId The region snapshotted on. * @param block Delta end at this block number, inclusive * @param cid IPFS CID of the delta file. */ event Delta(uint256 indexed regionId, uint256 indexed block, string cid); /** * @notice Snapshot info. */ struct SnapshotInfo { uint256 block; string cid; } /** * @dev Store each regions' latest snapshot info. */ mapping(uint256 => SnapshotInfo) private _latestSnapshots; /** * @notice Create Snapper contract. */ constructor() {} /** * @notice Intialize the region before taking further snapshots. * @dev Emits {Snapshot} event which used by Clients to draw initial picture. * @param regionId The region to intialize. * @param initBlock_ The Contract Creation block number of The Space contract. * @param snapshotCid_ The initial pixels picture IPFS CID of The Space. */ function initRegion( uint256 regionId, uint256 initBlock_, string calldata snapshotCid_ ) external onlyOwner { if (_latestSnapshots[regionId].block != 0) revert CannotBeReInitialized(regionId); _latestSnapshots[regionId].block = initBlock_; _latestSnapshots[regionId].cid = snapshotCid_; emit Snapshot(regionId, initBlock_, snapshotCid_); } /** * @notice Take a snapshot on the region. * @dev Emits {Snapshot} and {Delta} events. * @param regionId The region snapshotted on. * @param lastSnapshotBlock_ Last block number snapshotted for The Space. use to validate precondition. * @param targetSnapshotBlock_ The block number snapshotted for The Space this time. */ function takeSnapshot( uint256 regionId, uint256 lastSnapshotBlock_, uint256 targetSnapshotBlock_, string calldata snapshotCid_, string calldata deltaCid_ ) external onlyOwner { uint256 _latestSnapshotBlock = _latestSnapshots[regionId].block; if (lastSnapshotBlock_ != _latestSnapshotBlock || lastSnapshotBlock_ == 0) revert InvalidLastSnapshotBlock(regionId, lastSnapshotBlock_, _latestSnapshotBlock); if (targetSnapshotBlock_ <= _latestSnapshotBlock) revert InvalidTargetSnapshotBlock(regionId, targetSnapshotBlock_, _latestSnapshotBlock); _latestSnapshots[regionId].block = targetSnapshotBlock_; _latestSnapshots[regionId].cid = snapshotCid_; emit Snapshot(regionId, targetSnapshotBlock_, snapshotCid_); emit Delta(regionId, targetSnapshotBlock_, deltaCid_); } /** * @notice Get region 0 lastest snapshot info. */ function latestSnapshotInfo() external view returns (SnapshotInfo memory) { return _latestSnapshots[0]; } /** * @notice Get the lastest snapshot info by region. * @param regionId ID of the region to query. */ function latestSnapshotInfo(uint256 regionId) external view returns (SnapshotInfo memory) { return _latestSnapshots[regionId]; } }
* @notice Take a snapshot on the region. @dev Emits {Snapshot} and {Delta} events. @param regionId The region snapshotted on. @param lastSnapshotBlock_ Last block number snapshotted for The Space. use to validate precondition. @param targetSnapshotBlock_ The block number snapshotted for The Space this time./
function takeSnapshot( uint256 regionId, uint256 lastSnapshotBlock_, uint256 targetSnapshotBlock_, string calldata snapshotCid_, string calldata deltaCid_ ) external onlyOwner { uint256 _latestSnapshotBlock = _latestSnapshots[regionId].block; if (lastSnapshotBlock_ != _latestSnapshotBlock || lastSnapshotBlock_ == 0) revert InvalidLastSnapshotBlock(regionId, lastSnapshotBlock_, _latestSnapshotBlock); if (targetSnapshotBlock_ <= _latestSnapshotBlock) revert InvalidTargetSnapshotBlock(regionId, targetSnapshotBlock_, _latestSnapshotBlock); _latestSnapshots[regionId].block = targetSnapshotBlock_; _latestSnapshots[regionId].cid = snapshotCid_; emit Snapshot(regionId, targetSnapshotBlock_, snapshotCid_); emit Delta(regionId, targetSnapshotBlock_, deltaCid_); }
5,473,182
[ 1, 13391, 279, 4439, 603, 326, 3020, 18, 225, 7377, 1282, 288, 4568, 97, 471, 288, 9242, 97, 2641, 18, 225, 3020, 548, 1021, 3020, 4439, 2344, 603, 18, 225, 1142, 4568, 1768, 67, 6825, 1203, 1300, 4439, 2344, 364, 1021, 14059, 18, 999, 358, 1954, 24148, 18, 225, 1018, 4568, 1768, 67, 1021, 1203, 1300, 4439, 2344, 364, 1021, 14059, 333, 813, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4862, 4568, 12, 203, 3639, 2254, 5034, 3020, 548, 16, 203, 3639, 2254, 5034, 1142, 4568, 1768, 67, 16, 203, 3639, 2254, 5034, 1018, 4568, 1768, 67, 16, 203, 3639, 533, 745, 892, 4439, 19844, 67, 16, 203, 3639, 533, 745, 892, 3622, 19844, 67, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 389, 13550, 4568, 1768, 273, 389, 13550, 17095, 63, 6858, 548, 8009, 2629, 31, 203, 3639, 309, 261, 2722, 4568, 1768, 67, 480, 389, 13550, 4568, 1768, 747, 1142, 4568, 1768, 67, 422, 374, 13, 203, 5411, 15226, 1962, 3024, 4568, 1768, 12, 6858, 548, 16, 1142, 4568, 1768, 67, 16, 389, 13550, 4568, 1768, 1769, 203, 203, 3639, 309, 261, 3299, 4568, 1768, 67, 1648, 389, 13550, 4568, 1768, 13, 203, 5411, 15226, 1962, 2326, 4568, 1768, 12, 6858, 548, 16, 1018, 4568, 1768, 67, 16, 389, 13550, 4568, 1768, 1769, 203, 203, 3639, 389, 13550, 17095, 63, 6858, 548, 8009, 2629, 273, 1018, 4568, 1768, 67, 31, 203, 3639, 389, 13550, 17095, 63, 6858, 548, 8009, 13478, 273, 4439, 19844, 67, 31, 203, 203, 3639, 3626, 10030, 12, 6858, 548, 16, 1018, 4568, 1768, 67, 16, 4439, 19844, 67, 1769, 203, 3639, 3626, 17799, 12, 6858, 548, 16, 1018, 4568, 1768, 67, 16, 3622, 19844, 67, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-28 */ /** *Submitted for verification at Etherscan.io on 2022-02-24 */ /** *Submitted for verification at Etherscan.io on 2022-02-24 */ /** *Submitted for verification at Etherscan.io on 2022-02-10 */ /** *Submitted for verification at Etherscan.io on 2022-01-11 */ /** *Submitted for verification at Etherscan.io on 2021-10-30 */ // File: contracts/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ // constructor () internal { // _owner = msg.sender; // emit OwnershipTransferred(address(0), _owner); // } function ownerInit() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/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); function mint(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); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function blindBox(address seller, string calldata tokenURI, bool flag, address to, string calldata ownerId) external returns (uint256); function mintAliaForNonCrypto(uint256 price, address from) external returns (bool); function nonCryptoNFTVault() external returns(address); function mainPerecentage() external returns(uint256); function authorPercentage() external returns(uint256); function platformPerecentage() external returns(uint256); function updateAliaBalance(string calldata stringId, uint256 amount) external returns(bool); function getSellDetail(uint256 tokenId) external view returns (address, uint256, uint256, address, uint256, uint256, uint256); function getNonCryptoWallet(string calldata ownerId) external view returns(uint256); function getNonCryptoOwner(uint256 tokenId) external view returns(string memory); function adminOwner(address _address) external view returns(bool); function getAuthor(uint256 tokenIdFunction) external view returns (address); function _royality(uint256 tokenId) external view returns (uint256); function getrevenueAddressBlindBox(string calldata info) external view returns(address); function getboxNameByToken(uint256 token) external view returns(string memory); //Revenue share function addNonCryptoAuthor(string calldata artistId, uint256 tokenId, bool _isArtist) external returns(bool); function transferAliaArtist(address buyer, uint256 price, address nftVaultAddress, uint256 tokenId ) external returns(bool); function checkArtistOwner(string calldata artistId, uint256 tokenId) external returns(bool); function checkTokenAuthorIsArtist(uint256 tokenId) external returns(bool); function withdraw(uint) external; function deposit() payable external; // function approve(address spender, uint256 rawAmount) external; // BlindBox ref:https://noborderz.slack.com/archives/C0236PBG601/p1633942033011800?thread_ts=1633941154.010300&cid=C0236PBG601 function isSellable (string calldata name) external view returns(bool); function tokenURI(uint256 tokenId) external view returns (string memory); function ownerOf(uint256 tokenId) external view returns (address); function burn (uint256 tokenId) external; } // File: contracts/INFT.sol pragma solidity ^0.5.0; // import "../openzeppelin-solidity/contracts/token/ERC721/IERC721Full.sol"; interface INFT { function transferFromAdmin(address owner, address to, uint256 tokenId) external; function mintWithTokenURI(address to, string calldata tokenURI) external returns (uint256); function getAuthor(uint256 tokenIdFunction) external view returns (address); function updateTokenURI(uint256 tokenIdT, string calldata uriT) external; // function mint(address to, string calldata tokenURI) external returns (uint256); function transferOwnership(address newOwner) external; function ownerOf(uint256 tokenId) external view returns(address); function transferFrom(address owner, address to, uint256 tokenId) external; } // File: contracts/IFactory.sol pragma solidity ^0.5.0; contract IFactory { function create(string calldata name_, string calldata symbol_, address owner_) external returns(address); function getCollections(address owner_) external view returns(address [] memory); } // File: contracts/LPInterface.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 LPInterface { /** * @dev Returns the amount of tokens in existence. */ function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } // 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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/Proxy/DexStorage.sol pragma solidity ^0.5.0; /////////////////////////////////////////////////////////////////////////////////////////////////// /** * @title DexStorage * @dev Defining dex storage for the proxy contract. */ /////////////////////////////////////////////////////////////////////////////////////////////////// contract DexStorage { using SafeMath for uint256; address x; // dummy variable, never set or use its value in any logic contracts. It keeps garbage value & append it with any value set on it. IERC20 ALIA; INFT XNFT; IFactory factory; IERC20 OldNFTDex; IERC20 BUSD; IERC20 BNB; struct RDetails { address _address; uint256 percentage; } struct AuthorDetails { address _address; uint256 royalty; string ownerId; bool isSecondry; } // uint256[] public sellList; // this violates generlization as not tracking tokenIds agains nftContracts/collections but ignoring as not using it in logic anywhere (uncommented) mapping (uint256 => mapping(address => AuthorDetails)) internal _tokenAuthors; mapping (address => bool) public adminOwner; address payable public platform; address payable public authorVault; uint256 internal platformPerecentage; struct fixedSell { // address nftContract; // adding to support multiple NFT contracts buy/sell address seller; uint256 price; uint256 timestamp; bool isDollar; uint256 currencyType; } // stuct for auction struct auctionSell { address seller; address nftContract; address bidder; uint256 minPrice; uint256 startTime; uint256 endTime; uint256 bidAmount; bool isDollar; uint256 currencyType; // address nftAddress; } // tokenId => nftContract => fixedSell mapping (uint256 => mapping (address => fixedSell)) internal _saleTokens; mapping(address => bool) public _supportNft; // tokenId => nftContract => auctionSell mapping(uint256 => mapping ( address => auctionSell)) internal _auctionTokens; address payable public nonCryptoNFTVault; // tokenId => nftContract => ownerId mapping (uint256=> mapping (address => string)) internal _nonCryptoOwners; struct balances{ uint256 bnb; uint256 Alia; uint256 BUSD; } mapping (string => balances) internal _nonCryptoWallet; LPInterface LPAlia; LPInterface LPBNB; uint256 public adminDiscount; address admin; mapping (string => address) internal revenueAddressBlindBox; mapping (uint256=>string) internal boxNameByToken; bool public collectionConfig; uint256 public countCopy; mapping (uint256=> mapping( address => mapping(uint256 => bool))) _allowedCurrencies; IERC20 token; // struct offer { // address _address; // string ownerId; // uint256 currencyType; // uint256 price; // } // struct offers { // uint256 count; // mapping (uint256 => offer) _offer; // } // mapping(uint256 => mapping(address => offers)) _offers; uint256[] allowedArray; mapping (address => bool) collectionsWithRoyalties; address blindAddress; mapping(uint256 => mapping(address => bool)) isBlindNft; address private proxyOwner; //never use this variable } // File: contracts/SecondDexStorage.sol pragma solidity ^0.5.0; contract SecondDexStorage{ // Add new storage here mapping(uint256 => bool) blindNFTOpenForSale; mapping(uint256 => mapping(address => uint256)) seriesIds; } // File: contracts/BNFT.sol pragma solidity ^0.5.0; interface BNFT { function mint(address to_, uint256 countNFTs_) external returns (uint256, uint256); function burnAdmin(uint256 tokenId) external; function TransferFromAdmin(uint256 tokenId, address to) external; } // File: contracts/CollectionDex.sol pragma solidity ^0.5.0; contract BlindboxDex is Ownable, DexStorage, SecondDexStorage { event MintWithTokenURI(address indexed collection, uint256 indexed tokenId, address minter, string tokenURI); event SellNFT(address indexed from, address nft_a, uint256 tokenId, address seller, uint256 price, uint256 royalty, uint256 baseCurrency, uint256[] allowedCurrencies); event BuyNFT(address indexed from, address nft_a, uint256 tokenId, address buyer, uint256 price, uint256 baseCurrency, uint256 calculated, uint256 currencyType); event CancelSell(address indexed from, address nftContract, uint256 tokenId); event UpdatePrice(address indexed from, uint256 tokenId, uint256 newPrice, bool isDollar, address nftContract, uint256 baseCurrency, uint256[] allowedCurrencies); event BuyNFTNonCrypto( address indexed from, address nft_a, uint256 tokenId, string buyer, uint256 price, uint256 baseCurrency, uint256 calculated, uint256 currencyType); event TransferPackNonCrypto(address indexed from, string to, uint256 tokenId); event Claim(address indexed bidder, address nftContract, uint256 tokenId, uint256 amount, address seller, uint256 baseCurrency); event OnAuction(address indexed seller, address nftContract, uint256 indexed tokenId, uint256 startPrice, uint256 endTime, uint256 baseCurrency); constructor() public{ } function blindBoxMintedNFT(address collection, uint256[] memory tokenIds, uint256 royalty, address bankAddress ) public { require(admin == msg.sender, "not authorize"); for(uint256 i=0; i< tokenIds.length; i++){ _tokenAuthors[tokenIds[i]][collection]._address = bankAddress; _tokenAuthors[tokenIds[i]][collection].royalty = royalty; } } function mintBlindbox(address collection, address to, uint256 quantity, address from, uint256 royalty, uint256 seriesId) public returns(uint256 fromIndex,uint256 toIndex) { require(msg.sender == blindAddress, "not authorize"); (fromIndex, toIndex) = BNFT(collection).mint(to, quantity); for(uint256 i = fromIndex; i<= toIndex; i++){ _tokenAuthors[i][collection]._address = from; _tokenAuthors[i][collection].royalty = royalty; isBlindNft[i][collection] = true; seriesIds[i][collection] = seriesId; emit MintWithTokenURI(collection, i, to, ""); } } function setBlindSecondSaleClose(uint256 seriesId) public { require(admin == msg.sender, "no authorize"); blindNFTOpenForSale[seriesId] = false; } function setBlindSecondSaleOpen(uint256 seriesId) public { require(admin == msg.sender, "no authorize"); blindNFTOpenForSale[seriesId] = true; } modifier isValid( address collection_) { require(_supportNft[collection_],"unsupported collection"); _; } function getPercentages(uint256 tokenId, address nft_a) public view returns(uint256 mainPerecentage, uint256 authorPercentage, address blindRAddress) { if(nft_a == address(XNFT) || collectionsWithRoyalties[nft_a]) { // royality for XNFT only (non-user defined collection) if(_tokenAuthors[tokenId][nft_a].royalty > 0) { authorPercentage = _tokenAuthors[tokenId][nft_a].royalty; } else { authorPercentage = 25; } mainPerecentage = SafeMath.sub(SafeMath.sub(1000,authorPercentage),platformPerecentage); //50 } else { mainPerecentage = SafeMath.sub(1000, platformPerecentage); } blindRAddress = revenueAddressBlindBox[boxNameByToken[tokenId]]; if(blindRAddress != address(0x0)){ mainPerecentage = 865; authorPercentage =135; } } function claimAuction(address _contract, uint256 _tokenId, bool awardType, string memory ownerId, address from) isValid(_contract) public { auctionSell storage temp = _auctionTokens[_tokenId][_contract]; require(temp.endTime < now,"103"); require(temp.minPrice > 0,"104"); require(msg.sender==temp.bidder,"107"); INFT(temp.nftContract).transferFrom(address(this), temp.bidder, _tokenId); (uint256 mainPerecentage, uint256 authorPercentage, address blindRAddress) = getPercentages(_tokenId, _contract); if(temp.currencyType < 1){ uint256 price = SafeMath.div(temp.bidAmount,1000000000000); token = BUSD; //IERC20(address(ALIA)); if(blindRAddress == address(0x0)){ blindRAddress = _tokenAuthors[_tokenId][_contract]._address; token.transfer( platform, SafeMath.div(SafeMath.mul(price ,platformPerecentage ) , 1000)); } if(_contract == address(XNFT)){ // currently only supporting royality for non-user defined collection token.transfer( blindRAddress, SafeMath.div(SafeMath.mul(price ,authorPercentage ) , 1000)); } token.transfer( temp.seller, SafeMath.div(SafeMath.mul(price ,mainPerecentage ) , 1000)); }else { if(blindRAddress == address(0x0)){ blindRAddress = _tokenAuthors[_tokenId][_contract]._address; bnbTransferAuction( platform, platformPerecentage, temp.bidAmount); } if(_contract == address(XNFT) || collectionsWithRoyalties[_contract]){ // currently only supporting royality for non-user defined collection bnbTransferAuction( blindRAddress, authorPercentage, temp.bidAmount); } bnbTransferAuction( temp.seller, mainPerecentage, temp.bidAmount); } // in case of user-defined collection, sell will receive amount = bidAmount - platformPerecentage amount // author will get nothing as royality not tracking for user-defined collections emit Claim(temp.bidder, temp.nftContract, _tokenId, temp.bidAmount, temp.seller, temp.currencyType); delete _auctionTokens[_tokenId][_contract]; } function bnbTransferAuction(address _address, uint256 percentage, uint256 price) internal { address payable newAddress = address(uint160(_address)); uint256 initialBalance; uint256 newBalance; initialBalance = address(this).balance; BNB.withdraw((price / 1000) * percentage); newBalance = address(this).balance.sub(initialBalance); newAddress.transfer(newBalance); } function setOnAuction(address _contract,uint256 _tokenId, uint256 _minPrice, uint256 baseCurrency, uint256 _endTime) isValid(_contract) public { require(INFT(_contract).ownerOf(_tokenId) == msg.sender, "102"); require(!isBlindNft[_tokenId][_contract] || blindNFTOpenForSale[seriesIds[_tokenId][_contract]], "can't sell" ); // string storage boxName = boxNameByToken[_tokenId]; // require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); require(baseCurrency <= 1, "121"); // require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); _auctionTokens[_tokenId][_contract].seller = msg.sender; _auctionTokens[_tokenId][_contract].nftContract = _contract; _auctionTokens[_tokenId][_contract].minPrice = _minPrice; _auctionTokens[_tokenId][_contract].startTime = now; _auctionTokens[_tokenId][_contract].endTime = _endTime; _auctionTokens[_tokenId][_contract].currencyType = baseCurrency; INFT(_contract).transferFrom(msg.sender, address(this), _tokenId); emit OnAuction(msg.sender, _contract, _tokenId, _minPrice, _endTime, baseCurrency); } function sellNFT(address nft_a,uint256 tokenId, address seller, uint256 price, uint256 baseCurrency, uint256[] memory allowedCurrencies) isValid(nft_a) public{ require(msg.sender == admin || (msg.sender == seller && INFT(nft_a).ownerOf(tokenId) == seller), "101"); require(!isBlindNft[tokenId][nft_a] || blindNFTOpenForSale[seriesIds[tokenId][nft_a]], "can't sell" ); // string storage boxName = boxNameByToken[tokenId]; uint256 royality; require(baseCurrency <= 1, "121"); // require(revenueAddressBlindBox[boxName] == address(0x0) || IERC20(0x313Df3fE7c83d927D633b9a75e8A9580F59ae79B).isSellable(boxName), "112"); bool isValid = true; for(uint256 i = 0; i< allowedCurrencies.length; i++){ if(allowedCurrencies[i] > 1){ isValid = false; } _allowedCurrencies[tokenId][nft_a][allowedCurrencies[i]] = true; } require(isValid,"122"); _saleTokens[tokenId][nft_a].seller = seller; _saleTokens[tokenId][nft_a].price = price; _saleTokens[tokenId][nft_a].timestamp = now; // _saleTokens[tokenId][nft_a].isDollar = isDollar; _saleTokens[tokenId][nft_a].currencyType = baseCurrency; // need to check if it voilates generalization // sellList.push(tokenId); // dealing special case of escrowing for xanalia collection i.e XNFT if(nft_a == address(XNFT)){ msg.sender == admin ? XNFT.transferFromAdmin(seller, address(this), tokenId) : XNFT.transferFrom(seller, address(this), tokenId); royality = _tokenAuthors[tokenId][nft_a].royalty; } else { INFT(nft_a).transferFrom(seller, address(this), tokenId); royality = 0; // making it zero as not setting royality for user defined collection's NFT } emit SellNFT(msg.sender, nft_a, tokenId, seller, price, royality, baseCurrency, allowedCurrencies); } }
currently only supporting royality for non-user defined collection
if(_contract == address(XNFT) || collectionsWithRoyalties[_contract]){
5,737,121
[ 1, 2972, 715, 1338, 22930, 721, 93, 7919, 364, 1661, 17, 1355, 2553, 1849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 309, 24899, 16351, 422, 1758, 12, 60, 50, 4464, 13, 747, 6980, 1190, 54, 13372, 2390, 606, 63, 67, 16351, 5717, 95, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./libraries/DecimalsConverter.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IClaimingRegistry.sol"; import "./interfaces/IPolicyBook.sol"; import "./interfaces/IPolicyRegistry.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/ILeveragePortfolio.sol"; import "./interfaces/ICapitalPool.sol"; import "./interfaces/IClaimVoting.sol"; import "./abstract/AbstractDependant.sol"; import "./Globals.sol"; contract ClaimingRegistry is IClaimingRegistry, Initializable, AbstractDependant { using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; uint256 internal constant ANONYMOUS_VOTING_DURATION = 1 weeks; uint256 internal constant EXPOSE_VOTE_DURATION = 1 weeks; uint256 internal constant PRIVATE_CLAIM_DURATION = 3 days; uint256 internal constant VIEW_VERDICT_DURATION = 10 days; uint256 public constant READY_TO_WITHDRAW_PERIOD = 8 days; IPolicyRegistry public policyRegistry; address public claimVotingAddress; mapping(address => EnumerableSet.UintSet) internal _myClaims; // claimer -> claim indexes mapping(address => mapping(address => uint256)) internal _allClaimsToIndex; // book -> claimer -> index mapping(uint256 => ClaimInfo) internal _allClaimsByIndexInfo; // index -> info EnumerableSet.UintSet internal _pendingClaimsIndexes; EnumerableSet.UintSet internal _allClaimsIndexes; uint256 private _claimIndex; address internal policyBookAdminAddress; ICapitalPool public capitalPool; // claim withdraw EnumerableSet.UintSet internal _withdrawClaimRequestIndexList; mapping(uint256 => ClaimWithdrawalInfo) public override claimWithdrawalInfo; // index -> info //reward withdraw EnumerableSet.AddressSet internal _withdrawRewardRequestVoterList; mapping(address => RewardWithdrawalInfo) public override rewardWithdrawalInfo; // address -> info IClaimVoting public claimVoting; IPolicyBookRegistry public policyBookRegistry; mapping(address => EnumerableSet.UintSet) internal _policyBookClaims; // book -> index ERC20 public stblToken; uint256 public stblDecimals; event AppealPending(address claimer, address policyBookAddress, uint256 claimIndex); event ClaimPending(address claimer, address policyBookAddress, uint256 claimIndex); event ClaimAccepted( address claimer, address policyBookAddress, uint256 claimAmount, uint256 claimIndex ); event ClaimRejected(address claimer, address policyBookAddress, uint256 claimIndex); event ClaimExpired(address claimer, address policyBookAddress, uint256 claimIndex); event AppealRejected(address claimer, address policyBookAddress, uint256 claimIndex); event WithdrawalRequested( address _claimer, uint256 _claimRefundAmount, uint256 _readyToWithdrawDate ); event ClaimWithdrawn(address _claimer, uint256 _claimRefundAmount); event RewardWithdrawn(address _voter, uint256 _rewardAmount); modifier onlyClaimVoting() { require( claimVotingAddress == msg.sender, "ClaimingRegistry: Caller is not a ClaimVoting contract" ); _; } modifier onlyPolicyBookAdmin() { require( policyBookAdminAddress == msg.sender, "ClaimingRegistry: Caller is not a PolicyBookAdmin" ); _; } modifier withExistingClaim(uint256 index) { require(claimExists(index), "ClaimingRegistry: This claim doesn't exist"); _; } function __ClaimingRegistry_init() external initializer { _claimIndex = 1; } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { policyRegistry = IPolicyRegistry(_contractsRegistry.getPolicyRegistryContract()); claimVotingAddress = _contractsRegistry.getClaimVotingContract(); policyBookAdminAddress = _contractsRegistry.getPolicyBookAdminContract(); capitalPool = ICapitalPool(_contractsRegistry.getCapitalPoolContract()); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); claimVoting = IClaimVoting(_contractsRegistry.getClaimVotingContract()); stblToken = ERC20(_contractsRegistry.getUSDTContract()); stblDecimals = stblToken.decimals(); } function _isClaimAwaitingCalculation(uint256 index) internal view withExistingClaim(index) returns (bool) { return (_allClaimsByIndexInfo[index].status == ClaimStatus.PENDING && _allClaimsByIndexInfo[index].dateSubmitted.add(votingDuration(index)) <= block.timestamp); } function _isClaimAppealExpired(uint256 index) internal view withExistingClaim(index) returns (bool) { return (_allClaimsByIndexInfo[index].status == ClaimStatus.REJECTED_CAN_APPEAL && _allClaimsByIndexInfo[index].dateEnded.add(policyRegistry.STILL_CLAIMABLE_FOR()) <= block.timestamp); } function _isClaimExpired(uint256 index) internal view withExistingClaim(index) returns (bool) { return (_allClaimsByIndexInfo[index].status == ClaimStatus.PENDING && _allClaimsByIndexInfo[index].dateSubmitted.add(validityDuration(index)) <= block.timestamp); } function anonymousVotingDuration(uint256 index) public view override withExistingClaim(index) returns (uint256) { return ANONYMOUS_VOTING_DURATION; } function votingDuration(uint256 index) public view override returns (uint256) { return anonymousVotingDuration(index).add(EXPOSE_VOTE_DURATION); } function validityDuration(uint256 index) public view override withExistingClaim(index) returns (uint256) { return votingDuration(index).add(VIEW_VERDICT_DURATION); } function anyoneCanCalculateClaimResultAfter(uint256 index) public view override returns (uint256) { return votingDuration(index).add(PRIVATE_CLAIM_DURATION); } function canBuyNewPolicy(address buyer, address policyBookAddress) external override { bool previousEnded = !policyRegistry.isPolicyActive(buyer, policyBookAddress); uint256 index = _allClaimsToIndex[policyBookAddress][buyer]; require( (previousEnded && (!claimExists(index) || (!_pendingClaimsIndexes.contains(index) && claimStatus(index) != ClaimStatus.REJECTED_CAN_APPEAL))) || (!previousEnded && !claimExists(index)), "PB: Claim is pending" ); if (!previousEnded) { IPolicyBook(policyBookAddress).endActivePolicy(buyer); } } function canWithdrawLockedBMI(uint256 index) public view returns (bool) { return (_allClaimsByIndexInfo[index].status == ClaimStatus.EXPIRED) || (_allClaimsByIndexInfo[index].status == ClaimStatus.ACCEPTED && _withdrawClaimRequestIndexList.contains(index) && getClaimWithdrawalStatus(index) == WithdrawalStatus.EXPIRED && !policyRegistry.isPolicyActive( _allClaimsByIndexInfo[index].claimer, _allClaimsByIndexInfo[index].policyBookAddress )); } function getClaimWithdrawalStatus(uint256 index) public view override returns (WithdrawalStatus) { if (claimWithdrawalInfo[index].readyToWithdrawDate == 0) { return WithdrawalStatus.NONE; } if (block.timestamp < claimWithdrawalInfo[index].readyToWithdrawDate) { return WithdrawalStatus.PENDING; } if ( block.timestamp >= claimWithdrawalInfo[index].readyToWithdrawDate.add(READY_TO_WITHDRAW_PERIOD) ) { return WithdrawalStatus.EXPIRED; } return WithdrawalStatus.READY; } function getRewardWithdrawalStatus(address voter) public view override returns (WithdrawalStatus) { if (rewardWithdrawalInfo[voter].readyToWithdrawDate == 0) { return WithdrawalStatus.NONE; } if (block.timestamp < rewardWithdrawalInfo[voter].readyToWithdrawDate) { return WithdrawalStatus.PENDING; } if ( block.timestamp >= rewardWithdrawalInfo[voter].readyToWithdrawDate.add(READY_TO_WITHDRAW_PERIOD) ) { return WithdrawalStatus.EXPIRED; } return WithdrawalStatus.READY; } function hasProcedureOngoing(address poolAddress) external view override returns (bool) { if (policyBookRegistry.isUserLeveragePool(poolAddress)) { ILeveragePortfolio userLeveragePool = ILeveragePortfolio(poolAddress); address[] memory _coveragePools = userLeveragePool.listleveragedCoveragePools( 0, userLeveragePool.countleveragedCoveragePools() ); for (uint256 i = 0; i < _coveragePools.length; i++) { if (_hasProcedureOngoing(_coveragePools[i])) { return true; } } } else { if (_hasProcedureOngoing(poolAddress)) { return true; } } return false; } function _hasProcedureOngoing(address policyBookAddress) internal view returns (bool hasProcedure) { for (uint256 i = 0; i < _policyBookClaims[policyBookAddress].length(); i++) { uint256 index = _policyBookClaims[policyBookAddress].at(i); ClaimStatus status = claimStatus(index); address claimer = _allClaimsByIndexInfo[index].claimer; if ( !(status == ClaimStatus.EXPIRED || // has expired status == ClaimStatus.REJECTED || // has been rejected || appeal expired (status == ClaimStatus.ACCEPTED && getClaimWithdrawalStatus(index) == WithdrawalStatus.NONE) || // has been accepted and withdrawn or has withdrawn locked BMI at policy end (status == ClaimStatus.ACCEPTED && getClaimWithdrawalStatus(index) == WithdrawalStatus.EXPIRED && !policyRegistry.isPolicyActive(claimer, policyBookAddress))) // has been accepted and never withdrawn but cannot request withdraw anymore ) { return true; } } } function submitClaim( address claimer, address policyBookAddress, string calldata evidenceURI, uint256 cover, bool appeal ) external override onlyClaimVoting returns (uint256 _newClaimIndex) { uint256 index = _allClaimsToIndex[policyBookAddress][claimer]; ClaimStatus status = _myClaims[claimer].contains(index) ? claimStatus(index) : ClaimStatus.CAN_CLAIM; bool active = policyRegistry.isPolicyActive(claimer, policyBookAddress); /* (1) a new claim or a claim after rejected appeal (policy has to be active) * (2) a regular appeal (appeal should not be expired) * (3) a new claim cycle after expired appeal or a NEW policy when OLD one is accepted * (PB shall not allow user to buy new policy when claim is pending or REJECTED_CAN_APPEAL) * (policy has to be active) */ require( (!appeal && active && status == ClaimStatus.CAN_CLAIM) || (appeal && status == ClaimStatus.REJECTED_CAN_APPEAL) || (!appeal && active && status == ClaimStatus.EXPIRED) || (!appeal && active && (status == ClaimStatus.REJECTED || (policyRegistry.policyStartTime(claimer, policyBookAddress) > _allClaimsByIndexInfo[index].dateSubmitted && status == ClaimStatus.ACCEPTED))) || (!appeal && active && status == ClaimStatus.ACCEPTED && !_withdrawClaimRequestIndexList.contains(index)), "ClaimingRegistry: The claimer can't submit this claim" ); if (appeal) { _allClaimsByIndexInfo[index].status = ClaimStatus.REJECTED; } _myClaims[claimer].add(_claimIndex); _allClaimsToIndex[policyBookAddress][claimer] = _claimIndex; _policyBookClaims[policyBookAddress].add(_claimIndex); _allClaimsByIndexInfo[_claimIndex] = ClaimInfo( claimer, policyBookAddress, evidenceURI, block.timestamp, 0, appeal, ClaimStatus.PENDING, cover, 0 ); _pendingClaimsIndexes.add(_claimIndex); _allClaimsIndexes.add(_claimIndex); _newClaimIndex = _claimIndex++; if (!appeal) { emit ClaimPending(claimer, policyBookAddress, _newClaimIndex); } else { emit AppealPending(claimer, policyBookAddress, _newClaimIndex); } } function claimExists(uint256 index) public view override returns (bool) { return _allClaimsIndexes.contains(index); } function claimSubmittedTime(uint256 index) external view override returns (uint256) { return _allClaimsByIndexInfo[index].dateSubmitted; } function claimEndTime(uint256 index) external view override returns (uint256) { return _allClaimsByIndexInfo[index].dateEnded; } function isClaimAnonymouslyVotable(uint256 index) external view override returns (bool) { return (_pendingClaimsIndexes.contains(index) && _allClaimsByIndexInfo[index].dateSubmitted.add(anonymousVotingDuration(index)) > block.timestamp); } function isClaimExposablyVotable(uint256 index) external view override returns (bool) { if (!_pendingClaimsIndexes.contains(index)) { return false; } uint256 dateSubmitted = _allClaimsByIndexInfo[index].dateSubmitted; uint256 anonymousDuration = anonymousVotingDuration(index); return (dateSubmitted.add(anonymousDuration.add(EXPOSE_VOTE_DURATION)) > block.timestamp && dateSubmitted.add(anonymousDuration) < block.timestamp); } function isClaimVotable(uint256 index) external view override returns (bool) { return (_pendingClaimsIndexes.contains(index) && _allClaimsByIndexInfo[index].dateSubmitted.add(votingDuration(index)) > block.timestamp); } function canClaimBeCalculatedByAnyone(uint256 index) external view override returns (bool) { return _allClaimsByIndexInfo[index].status == ClaimStatus.PENDING && _allClaimsByIndexInfo[index].dateSubmitted.add( anyoneCanCalculateClaimResultAfter(index) ) <= block.timestamp; } function isClaimPending(uint256 index) external view override returns (bool) { return _pendingClaimsIndexes.contains(index); } function countPolicyClaimerClaims(address claimer) external view override returns (uint256) { return _myClaims[claimer].length(); } function countPendingClaims() external view override returns (uint256) { return _pendingClaimsIndexes.length(); } function countClaims() external view override returns (uint256) { return _allClaimsIndexes.length(); } /// @notice Gets the the claim index for for the users claim at an indexed position /// @param claimer address of of the user /// @param orderIndex uint256, numeric value for index /// @return uint256 function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view override returns (uint256) { return _myClaims[claimer].at(orderIndex); } function pendingClaimIndexAt(uint256 orderIndex) external view override returns (uint256) { return _pendingClaimsIndexes.at(orderIndex); } function claimIndexAt(uint256 orderIndex) external view override returns (uint256) { return _allClaimsIndexes.at(orderIndex); } function claimIndex(address claimer, address policyBookAddress) external view override returns (uint256) { return _allClaimsToIndex[policyBookAddress][claimer]; } function isClaimAppeal(uint256 index) external view override returns (bool) { return _allClaimsByIndexInfo[index].appeal; } function policyStatus(address claimer, address policyBookAddress) external view override returns (ClaimStatus) { if (!policyRegistry.isPolicyActive(claimer, policyBookAddress)) { return ClaimStatus.UNCLAIMABLE; } uint256 index = _allClaimsToIndex[policyBookAddress][claimer]; if (!_myClaims[claimer].contains(index)) { return ClaimStatus.CAN_CLAIM; } ClaimStatus status = claimStatus(index); bool newPolicyBought = policyRegistry.policyStartTime(claimer, policyBookAddress) > _allClaimsByIndexInfo[index].dateSubmitted; if ( status == ClaimStatus.REJECTED || status == ClaimStatus.EXPIRED || (newPolicyBought && status == ClaimStatus.ACCEPTED) ) { return ClaimStatus.CAN_CLAIM; } return status; } function claimStatus(uint256 index) public view override returns (ClaimStatus) { if (_isClaimAppealExpired(index)) { return ClaimStatus.REJECTED; } if (_isClaimExpired(index)) { return ClaimStatus.EXPIRED; } if (_isClaimAwaitingCalculation(index)) { return ClaimStatus.AWAITING_CALCULATION; } return _allClaimsByIndexInfo[index].status; } function claimOwner(uint256 index) external view override returns (address) { return _allClaimsByIndexInfo[index].claimer; } /// @notice Gets the policybook address of a claim with a certain index /// @param index uint256, numeric index value /// @return address function claimPolicyBook(uint256 index) external view override returns (address) { return _allClaimsByIndexInfo[index].policyBookAddress; } /// @notice gets the full claim information at a particular index. /// @param index uint256, numeric index value /// @return _claimInfo ClaimInfo function claimInfo(uint256 index) external view override withExistingClaim(index) returns (ClaimInfo memory _claimInfo) { _claimInfo = ClaimInfo( _allClaimsByIndexInfo[index].claimer, _allClaimsByIndexInfo[index].policyBookAddress, _allClaimsByIndexInfo[index].evidenceURI, _allClaimsByIndexInfo[index].dateSubmitted, _allClaimsByIndexInfo[index].dateEnded, _allClaimsByIndexInfo[index].appeal, claimStatus(index), _allClaimsByIndexInfo[index].claimAmount, _allClaimsByIndexInfo[index].claimRefund ); } /// @notice fetches the pending claims amounts which is before awaiting for calculation by 24 hrs /// @return _totalClaimsAmount uint256 collect claim amounts from pending claims function getAllPendingClaimsAmount() external view override returns (uint256 _totalClaimsAmount) { WithdrawalStatus _currentStatus; uint256 index; for (uint256 i = 0; i < _withdrawClaimRequestIndexList.length(); i++) { index = _withdrawClaimRequestIndexList.at(i); _currentStatus = getClaimWithdrawalStatus(index); if ( _currentStatus == WithdrawalStatus.NONE || _currentStatus == WithdrawalStatus.EXPIRED ) { continue; } ///@dev exclude all ready request until before ready to withdraw date by 24 hrs /// + 1 hr (spare time for transaction execution time) if ( block.timestamp >= claimWithdrawalInfo[index].readyToWithdrawDate.sub( ICapitalPool(capitalPool).rebalanceDuration().add(60 * 60) ) ) { _totalClaimsAmount = _totalClaimsAmount.add( _allClaimsByIndexInfo[index].claimRefund ); } } } function getAllPendingRewardsAmount() external view override returns (uint256 _totalRewardsAmount) { WithdrawalStatus _currentStatus; address voter; for (uint256 i = 0; i < _withdrawRewardRequestVoterList.length(); i++) { voter = _withdrawRewardRequestVoterList.at(i); _currentStatus = getRewardWithdrawalStatus(voter); if ( _currentStatus == WithdrawalStatus.NONE || _currentStatus == WithdrawalStatus.EXPIRED ) { continue; } ///@dev exclude all ready request until before ready to withdraw date by 24 hrs /// + 1 hr (spare time for transaction execution time) if ( block.timestamp >= rewardWithdrawalInfo[voter].readyToWithdrawDate.sub( ICapitalPool(capitalPool).rebalanceDuration().add(60 * 60) ) ) { _totalRewardsAmount = _totalRewardsAmount.add( rewardWithdrawalInfo[voter].rewardAmount ); } } } /// @notice gets the claiming balance from a list of claim indexes /// @param _claimIndexes uint256[], list of claimIndexes /// @return uint256 function getClaimableAmounts(uint256[] memory _claimIndexes) external view override returns (uint256) { uint256 _acumulatedClaimAmount; for (uint256 i = 0; i < _claimIndexes.length; i++) { _acumulatedClaimAmount = _acumulatedClaimAmount.add( _allClaimsByIndexInfo[i].claimAmount ); } return _acumulatedClaimAmount; } function _modifyClaim(uint256 index, ClaimStatus status) internal { address claimer = _allClaimsByIndexInfo[index].claimer; address policyBookAddress = _allClaimsByIndexInfo[index].policyBookAddress; uint256 claimAmount = _allClaimsByIndexInfo[index].claimAmount; if (status == ClaimStatus.ACCEPTED) { _allClaimsByIndexInfo[index].status = ClaimStatus.ACCEPTED; _requestClaimWithdrawal(claimer, index); emit ClaimAccepted(claimer, policyBookAddress, claimAmount, index); } else if (status == ClaimStatus.EXPIRED) { _allClaimsByIndexInfo[index].status = ClaimStatus.EXPIRED; emit ClaimExpired(claimer, policyBookAdminAddress, index); } else if (!_allClaimsByIndexInfo[index].appeal) { _allClaimsByIndexInfo[index].status = ClaimStatus.REJECTED_CAN_APPEAL; emit ClaimRejected(claimer, policyBookAddress, index); } else { _allClaimsByIndexInfo[index].status = ClaimStatus.REJECTED; delete _allClaimsToIndex[policyBookAddress][claimer]; _policyBookClaims[policyBookAddress].remove(index); emit AppealRejected(claimer, policyBookAddress, index); } _allClaimsByIndexInfo[index].dateEnded = block.timestamp; _pendingClaimsIndexes.remove(index); IPolicyBook(_allClaimsByIndexInfo[index].policyBookAddress).commitClaim( claimer, block.timestamp, _allClaimsByIndexInfo[index].status // ACCEPTED, REJECTED_CAN_APPEAL, REJECTED, EXPIRED ); } function acceptClaim(uint256 index, uint256 amount) external override onlyClaimVoting { require(_isClaimAwaitingCalculation(index), "ClaimingRegistry: The claim is not awaiting"); _allClaimsByIndexInfo[index].claimRefund = amount; _modifyClaim(index, ClaimStatus.ACCEPTED); } function rejectClaim(uint256 index) external override onlyClaimVoting { require(_isClaimAwaitingCalculation(index), "ClaimingRegistry: The claim is not awaiting"); _modifyClaim(index, ClaimStatus.REJECTED); } function expireClaim(uint256 index) external override onlyClaimVoting { require(_isClaimExpired(index), "ClaimingRegistry: The claim is not expired"); _modifyClaim(index, ClaimStatus.EXPIRED); } /// @notice Update Image Uri in case it contains material that is ilegal /// or offensive. /// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri. /// @param claim_Index Claim Index that is going to be updated /// @param _newEvidenceURI New evidence uri. It can be blank. function updateImageUriOfClaim(uint256 claim_Index, string calldata _newEvidenceURI) external override onlyPolicyBookAdmin { _allClaimsByIndexInfo[claim_Index].evidenceURI = _newEvidenceURI; } function requestClaimWithdrawal(uint256 index) external override { require( claimStatus(index) == IClaimingRegistry.ClaimStatus.ACCEPTED, "ClaimingRegistry: Claim is not accepted" ); address claimer = _allClaimsByIndexInfo[index].claimer; require(msg.sender == claimer, "ClaimingRegistry: Not allowed to request"); address policyBookAddress = _allClaimsByIndexInfo[index].policyBookAddress; require( policyRegistry.isPolicyActive(claimer, policyBookAddress) && policyRegistry.policyStartTime(claimer, policyBookAddress) < _allClaimsByIndexInfo[index].dateEnded, "ClaimingRegistry: The policy is expired" ); require( getClaimWithdrawalStatus(index) == WithdrawalStatus.NONE || getClaimWithdrawalStatus(index) == WithdrawalStatus.EXPIRED, "ClaimingRegistry: The claim is already requested" ); _requestClaimWithdrawal(claimer, index); } function _requestClaimWithdrawal(address claimer, uint256 index) internal { _withdrawClaimRequestIndexList.add(index); uint256 _readyToWithdrawDate = block.timestamp.add(capitalPool.getWithdrawPeriod()); bool _committed = claimWithdrawalInfo[index].committed; claimWithdrawalInfo[index] = ClaimWithdrawalInfo(_readyToWithdrawDate, _committed); emit WithdrawalRequested( claimer, _allClaimsByIndexInfo[index].claimRefund, _readyToWithdrawDate ); } function requestRewardWithdrawal(address voter, uint256 rewardAmount) external override onlyClaimVoting { require( getRewardWithdrawalStatus(voter) == WithdrawalStatus.NONE || getRewardWithdrawalStatus(voter) == WithdrawalStatus.EXPIRED, "ClaimingRegistry: The reward is already requested" ); _requestRewardWithdrawal(voter, rewardAmount); } function _requestRewardWithdrawal(address voter, uint256 rewardAmount) internal { _withdrawRewardRequestVoterList.add(voter); uint256 _readyToWithdrawDate = block.timestamp.add(capitalPool.getWithdrawPeriod()); rewardWithdrawalInfo[voter] = RewardWithdrawalInfo(rewardAmount, _readyToWithdrawDate); emit WithdrawalRequested(voter, rewardAmount, _readyToWithdrawDate); } function withdrawClaim(uint256 index) public virtual { address claimer = _allClaimsByIndexInfo[index].claimer; require(claimer == msg.sender, "ClaimingRegistry: Not the claimer"); require( getClaimWithdrawalStatus(index) == WithdrawalStatus.READY, "ClaimingRegistry: Withdrawal is not ready" ); address policyBookAddress = _allClaimsByIndexInfo[index].policyBookAddress; uint256 claimRefundConverted = DecimalsConverter.convertFrom18( _allClaimsByIndexInfo[index].claimRefund, stblDecimals ); uint256 _actualAmount = capitalPool.fundClaim(claimer, claimRefundConverted, policyBookAddress); claimRefundConverted = claimRefundConverted.sub(_actualAmount); if (!claimWithdrawalInfo[index].committed) { IPolicyBook(policyBookAddress).commitWithdrawnClaim(msg.sender); claimWithdrawalInfo[index].committed = true; } if (claimRefundConverted == 0) { _allClaimsByIndexInfo[index].claimRefund = 0; _withdrawClaimRequestIndexList.remove(index); delete claimWithdrawalInfo[index]; } else { _allClaimsByIndexInfo[index].claimRefund = DecimalsConverter.convertTo18( claimRefundConverted, stblDecimals ); _requestClaimWithdrawal(claimer, index); } claimVoting.transferLockedBMI(index, claimer); emit ClaimWithdrawn( msg.sender, DecimalsConverter.convertTo18(_actualAmount, stblDecimals) ); } function withdrawReward() public { require( getRewardWithdrawalStatus(msg.sender) == WithdrawalStatus.READY, "ClaimingRegistry: Withdrawal is not ready" ); uint256 rewardAmountConverted = DecimalsConverter.convertFrom18( rewardWithdrawalInfo[msg.sender].rewardAmount, stblDecimals ); uint256 _actualAmount = capitalPool.fundReward(msg.sender, rewardAmountConverted); rewardAmountConverted = rewardAmountConverted.sub(_actualAmount); if (rewardAmountConverted == 0) { rewardWithdrawalInfo[msg.sender].rewardAmount = 0; _withdrawRewardRequestVoterList.remove(msg.sender); delete rewardWithdrawalInfo[msg.sender]; } else { rewardWithdrawalInfo[msg.sender].rewardAmount = DecimalsConverter.convertTo18( rewardAmountConverted, stblDecimals ); _requestRewardWithdrawal(msg.sender, rewardWithdrawalInfo[msg.sender].rewardAmount); } emit RewardWithdrawn( msg.sender, DecimalsConverter.convertTo18(_actualAmount, stblDecimals) ); } function withdrawLockedBMI(uint256 index) public virtual { address claimer = _allClaimsByIndexInfo[index].claimer; require(claimer == msg.sender, "ClaimingRegistry: Not the claimer"); require( canWithdrawLockedBMI(index), "ClaimingRegistry: Claim is not expired or can still be withdrawn" ); address policyBookAddress = _allClaimsByIndexInfo[index].policyBookAddress; if (claimStatus(index) == ClaimStatus.ACCEPTED) { IPolicyBook(policyBookAddress).commitWithdrawnClaim(claimer); _withdrawClaimRequestIndexList.remove(index); delete claimWithdrawalInfo[index]; } claimVoting.transferLockedBMI(index, claimer); } /// @dev return maj and min with 10**5 precision, to get % divide by 10**3 function getRepartition(uint256 index) external view returns (uint256 maj, uint256 min) { uint256 voteCount = claimVoting.countVoteOnClaim(index); if (voteCount != 0) { for (uint256 i = 0; i < voteCount; i++) { uint256 voteIndex = claimVoting.voteIndexByClaimIndexAt(index, i); if (claimVoting.voteStatus(voteIndex) == IClaimVoting.VoteStatus.MAJORITY) { maj = maj.add(1); } else if (claimVoting.voteStatus(voteIndex) == IClaimVoting.VoteStatus.MINORITY) { min = min.add(1); } } maj = maj.mul(10**5).div(voteCount); min = min.mul(10**5).div(voteCount); } } }
@notice Gets the policybook address of a claim with a certain index @param index uint256, numeric index value @return address
function claimPolicyBook(uint256 index) external view override returns (address) { return _allClaimsByIndexInfo[index].policyBookAddress; }
5,469,918
[ 1, 3002, 326, 3329, 3618, 1758, 434, 279, 7516, 598, 279, 8626, 770, 225, 770, 2254, 5034, 16, 6389, 770, 460, 327, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 2582, 9084, 12, 11890, 5034, 770, 13, 3903, 1476, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 454, 15925, 21268, 966, 63, 1615, 8009, 5086, 9084, 1887, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xba629E206dfB3C6b1B874e6f44a734EAdbE75bEF/sources/contracts/core/PoolRebalanceHelper.sol
* PoolRebalanceHelper ============ Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are require to move funds. Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction. The signatures are created on the operation hash and passed to withdrawETH/withdrawERC20 The signer is determined by ECDSA.recover(). The signature is created with ethereumjs-util.ecsign(operationHash). Like the eth_sign RPC call, it packs the values as a 65-byte array of [r, s, v]. Unlike eth_sign, the message is not prefixed./ Events Public fields
contract PoolRebalanceHelper is ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; event Deposit(address token, uint256 amount, uint256 starkKey, uint256 positionId); event WithdrawETH(uint256 orderId, address to, uint256 amount); event WithdrawERC20(uint256 orderId, address token, address to, uint256 amount); pragma solidity ^0.8.0; struct order{ } constructor(address[] memory allowedSigners, address usdc,address starkex, uint256 assetType,uint256 l2poolAccountId, uint256 l2poolStarkKey) { require(allowedSigners.length == 3, "invalid allSigners length"); require(allowedSigners[0] != allowedSigners[1], "must be different signers"); require(allowedSigners[0] != allowedSigners[2], "must be different signers"); require(allowedSigners[1] != allowedSigners[2], "must be different signers"); require(usdc != address(0), "invalid usdc address"); require(block.chainid == 1 || block.chainid == 5, "invalid chain id"); signers = allowedSigners; USDC_ADDRESS = usdc; STARKEX_ADDRESS = starkex; ASSET_TYPE = assetType; L2POOL_ACCOUNT_ID = l2poolAccountId; L2POOL_STARK_KEY = l2poolStarkKey; } receive() external payable { } function deposit() public nonReentrant returns (uint256) { uint256 balance = IERC20(USDC_ADDRESS).balanceOf(address(this)); require(balance > 0, "insufficient balance"); require(block.chainid == 1 || block.chainid == 5, "invalid chain id"); IERC20(USDC_ADDRESS).safeApprove(STARKEX_ADDRESS, 0); IERC20(USDC_ADDRESS).safeApprove(STARKEX_ADDRESS, balance); IStarkEx starkEx = IStarkEx(STARKEX_ADDRESS); starkEx.depositERC20(L2POOL_STARK_KEY, ASSET_TYPE, L2POOL_ACCOUNT_ID, balance); emit Deposit( address(USDC_ADDRESS), balance, L2POOL_STARK_KEY, L2POOL_ACCOUNT_ID ); return balance; } function withdrawETH( address payable to, uint256 amount, uint256 expireTime, uint256 orderId, address[] memory allSigners, bytes[] memory signatures ) public nonReentrant { require(allSigners.length >= 2, "invalid allSigners length"); require(allSigners.length == signatures.length, "invalid signatures length"); require(expireTime >= block.timestamp,"expired transaction"); bytes32 operationHash = keccak256(abi.encodePacked("ETHER", to, amount, expireTime, orderId, address(this), block.chainid)); operationHash = ECDSA.toEthSignedMessageHash(operationHash); for (uint8 index = 0; index < allSigners.length; index++) { address signer = ECDSA.recover(operationHash, signatures[index]); require(signer == allSigners[index], "invalid signer"); require(isAllowedSigner(signer), "not allowed signer"); } require(success, "Address: unable to send value, recipient may have reverted"); emit WithdrawETH(orderId, to, amount); } function withdrawETH( address payable to, uint256 amount, uint256 expireTime, uint256 orderId, address[] memory allSigners, bytes[] memory signatures ) public nonReentrant { require(allSigners.length >= 2, "invalid allSigners length"); require(allSigners.length == signatures.length, "invalid signatures length"); require(expireTime >= block.timestamp,"expired transaction"); bytes32 operationHash = keccak256(abi.encodePacked("ETHER", to, amount, expireTime, orderId, address(this), block.chainid)); operationHash = ECDSA.toEthSignedMessageHash(operationHash); for (uint8 index = 0; index < allSigners.length; index++) { address signer = ECDSA.recover(operationHash, signatures[index]); require(signer == allSigners[index], "invalid signer"); require(isAllowedSigner(signer), "not allowed signer"); } require(success, "Address: unable to send value, recipient may have reverted"); emit WithdrawETH(orderId, to, amount); } tryInsertOrderId(orderId, to, amount, address(0)); require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = to.call{value: amount}(""); function withdrawErc20( address to, uint256 amount, address token, uint256 expireTime, uint256 orderId, address[] memory allSigners, bytes[] memory signatures ) public nonReentrant { require(allSigners.length >=2, "invalid allSigners length"); require(allSigners.length == signatures.length, "invalid signatures length"); require(expireTime >= block.timestamp,"expired transaction"); bytes32 operationHash = keccak256(abi.encodePacked("ERC20", to, amount, token, expireTime, orderId, address(this), block.chainid)); operationHash = ECDSA.toEthSignedMessageHash(operationHash); for (uint8 index = 0; index < allSigners.length; index++) { address signer = ECDSA.recover(operationHash, signatures[index]); require(signer == allSigners[index], "invalid signer"); require(isAllowedSigner(signer),"not allowed signer"); } emit WithdrawERC20(orderId, token, to, amount); } function withdrawErc20( address to, uint256 amount, address token, uint256 expireTime, uint256 orderId, address[] memory allSigners, bytes[] memory signatures ) public nonReentrant { require(allSigners.length >=2, "invalid allSigners length"); require(allSigners.length == signatures.length, "invalid signatures length"); require(expireTime >= block.timestamp,"expired transaction"); bytes32 operationHash = keccak256(abi.encodePacked("ERC20", to, amount, token, expireTime, orderId, address(this), block.chainid)); operationHash = ECDSA.toEthSignedMessageHash(operationHash); for (uint8 index = 0; index < allSigners.length; index++) { address signer = ECDSA.recover(operationHash, signatures[index]); require(signer == allSigners[index], "invalid signer"); require(isAllowedSigner(signer),"not allowed signer"); } emit WithdrawERC20(orderId, token, to, amount); } tryInsertOrderId(orderId, to, amount, token); IERC20(token).safeTransfer(to, amount); function isAllowedSigner(address signer) public view returns (bool) { for (uint i = 0; i < signers.length; i++) { if (signers[i] == signer) { return true; } } return false; } function isAllowedSigner(address signer) public view returns (bool) { for (uint i = 0; i < signers.length; i++) { if (signers[i] == signer) { return true; } } return false; } function isAllowedSigner(address signer) public view returns (bool) { for (uint i = 0; i < signers.length; i++) { if (signers[i] == signer) { return true; } } return false; } function tryInsertOrderId( uint256 orderId, address to, uint256 amount, address token ) internal { if (orders[orderId].executed) { revert("repeated order"); } orders[orderId].executed = true; orders[orderId].to = to; orders[orderId].amount = amount; orders[orderId].token = token; } function tryInsertOrderId( uint256 orderId, address to, uint256 amount, address token ) internal { if (orders[orderId].executed) { revert("repeated order"); } orders[orderId].executed = true; orders[orderId].to = to; orders[orderId].amount = amount; orders[orderId].token = token; } function calcSigHash( address to, uint256 amount, address token, uint256 expireTime, uint256 orderId) public view returns (bytes32) { bytes32 operationHash; if (token == address(0)) { operationHash = keccak256(abi.encodePacked("ETHER", to, amount, expireTime, orderId, address(this), block.chainid)); operationHash = keccak256(abi.encodePacked("ERC20", to, amount, token, expireTime, orderId, address(this), block.chainid)); } return operationHash; } function calcSigHash( address to, uint256 amount, address token, uint256 expireTime, uint256 orderId) public view returns (bytes32) { bytes32 operationHash; if (token == address(0)) { operationHash = keccak256(abi.encodePacked("ETHER", to, amount, expireTime, orderId, address(this), block.chainid)); operationHash = keccak256(abi.encodePacked("ERC20", to, amount, token, expireTime, orderId, address(this), block.chainid)); } return operationHash; } } else { }
2,971,075
[ 1, 2864, 426, 12296, 2276, 422, 1432, 631, 7651, 3309, 17, 2977, 264, 9230, 26584, 364, 999, 316, 279, 1825, 17, 26907, 3330, 1625, 576, 14862, 854, 2583, 358, 3635, 284, 19156, 18, 30195, 1399, 316, 279, 576, 17, 792, 17, 23, 10611, 1664, 18, 14854, 425, 1793, 3165, 358, 1699, 364, 576, 14862, 316, 279, 2202, 2492, 18, 1021, 14862, 854, 2522, 603, 326, 1674, 1651, 471, 2275, 358, 598, 9446, 1584, 44, 19, 1918, 9446, 654, 39, 3462, 1021, 10363, 353, 11383, 635, 7773, 19748, 18, 266, 3165, 7675, 1021, 3372, 353, 2522, 598, 13750, 822, 379, 2924, 17, 1367, 18, 557, 2977, 12, 7624, 2310, 2934, 23078, 326, 13750, 67, 2977, 8295, 745, 16, 518, 2298, 87, 326, 924, 487, 279, 15892, 17, 7229, 526, 434, 306, 86, 16, 272, 16, 331, 8009, 25448, 13750, 67, 2977, 16, 326, 883, 353, 486, 12829, 18, 19, 9043, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 8828, 426, 12296, 2276, 353, 868, 8230, 12514, 16709, 288, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 871, 4019, 538, 305, 12, 2867, 1147, 16, 2254, 5034, 3844, 16, 2254, 5034, 384, 1313, 653, 16, 2254, 5034, 1754, 548, 1769, 203, 225, 871, 3423, 9446, 1584, 44, 12, 11890, 5034, 20944, 16, 1758, 358, 16, 2254, 5034, 3844, 1769, 203, 225, 871, 3423, 9446, 654, 39, 3462, 12, 11890, 5034, 20944, 16, 1758, 1147, 16, 1758, 358, 16, 2254, 5034, 3844, 1769, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 225, 1958, 1353, 95, 203, 225, 289, 203, 203, 225, 3885, 12, 2867, 8526, 3778, 2935, 2766, 414, 16, 1758, 584, 7201, 16, 2867, 384, 1313, 338, 16, 225, 2254, 5034, 3310, 559, 16, 11890, 5034, 328, 22, 6011, 14594, 16, 2254, 5034, 328, 22, 6011, 510, 1313, 653, 13, 288, 203, 565, 2583, 12, 8151, 2766, 414, 18, 2469, 422, 890, 16, 315, 5387, 777, 2766, 414, 769, 8863, 203, 565, 2583, 12, 8151, 2766, 414, 63, 20, 65, 480, 2935, 2766, 414, 63, 21, 6487, 315, 11926, 506, 3775, 1573, 414, 8863, 203, 565, 2583, 12, 8151, 2766, 414, 63, 20, 65, 480, 2935, 2766, 414, 63, 22, 6487, 315, 11926, 506, 3775, 1573, 414, 8863, 203, 565, 2583, 12, 8151, 2766, 414, 63, 21, 65, 480, 2935, 2766, 414, 63, 22, 6487, 315, 11926, 2 ]
./full_match/1/0x2d68676c40Bf820Eb84e3B7d8d77a1C473b08B61/sources/contracts/crossChainSwaps/CrossChainSwapsSignatureUtil.sol
@dev Check the signature if the gas forwarding info is valid or not. @param _forwardingGas forwarding gas info @param signature forwardingGas signature
function _verifyForwardingGasSignature( ForwardingGas calldata _forwardingGas, bytes memory signature ) internal view { bytes32 forwardingGasHash = keccak256( abi.encode( FORWARDING_GAS_TYPE_HASH, _forwardingGas.forwardingValue, _forwardingGas.nonce, _forwardingGas.owner ) ); address signer = _hashTypedDataV4(forwardingGasHash).recover(signature); if (_forwardingGas.owner != signer) { revert SigningUtilsError( SigningUtilsErrorCodes.INVALID_GAS_FORWARDING_SIGNATURE ); } }
17,067,150
[ 1, 1564, 326, 3372, 309, 326, 16189, 20635, 1123, 353, 923, 578, 486, 18, 225, 389, 11565, 310, 27998, 20635, 16189, 1123, 225, 3372, 20635, 27998, 3372, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8705, 21487, 27998, 5374, 12, 203, 3639, 17206, 310, 27998, 745, 892, 389, 11565, 310, 27998, 16, 203, 3639, 1731, 3778, 3372, 203, 565, 262, 2713, 1476, 288, 203, 3639, 1731, 1578, 20635, 27998, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 12108, 21343, 1360, 67, 43, 3033, 67, 2399, 67, 15920, 16, 203, 7734, 389, 11565, 310, 27998, 18, 11565, 310, 620, 16, 203, 7734, 389, 11565, 310, 27998, 18, 12824, 16, 203, 7734, 389, 11565, 310, 27998, 18, 8443, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1758, 10363, 273, 389, 2816, 11985, 751, 58, 24, 12, 11565, 310, 27998, 2310, 2934, 266, 3165, 12, 8195, 1769, 203, 3639, 309, 261, 67, 11565, 310, 27998, 18, 8443, 480, 10363, 13, 288, 203, 5411, 15226, 20253, 1989, 668, 12, 203, 7734, 20253, 1989, 668, 6295, 18, 9347, 67, 43, 3033, 67, 7473, 21343, 1360, 67, 26587, 203, 5411, 11272, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.15; // SPDX-License-Identifier: Apache-2.0 library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } library Address { function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library Counters { using SafeMath for uint256; struct Counter { uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } interface ITRC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } contract ITRC721 is ITRC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) public; function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } contract ITRC721Metadata is ITRC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } contract ITRC721Receiver { function onTRC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } contract TRC165 is ITRC165 { bytes4 private constant _INTERFACE_ID_TRC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { _registerInterface(_INTERFACE_ID_TRC165); } function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "TRC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } contract TRC721 is Context, TRC165, ITRC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onTRC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ITRC721Receiver(0).onTRC721Received.selector` // // NOTE: TRC721 uses 0x150b7a02, TRC721 uses 0x5175f878. bytes4 private constant _TRC721_RECEIVED = 0x5175f878; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_TRC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to TRC721 via TRC165 _registerInterface(_INTERFACE_ID_TRC721); } function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "TRC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "TRC721: owner query for nonexistent token"); return owner; } function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "TRC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "TRC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "TRC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "TRC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "TRC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "TRC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnTRC721Received(from, to, tokenId, _data), "TRC721: transfer to non TRC721Receiver implementer"); } function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "TRC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnTRC721Received(address(0), to, tokenId, _data), "TRC721: transfer to non TRC721Receiver implementer"); } function _mint(address to, uint256 tokenId) internal { require(to != address(0), "TRC721: mint to the zero address"); require(!_exists(tokenId), "TRC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "TRC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "TRC721: transfer of token that is not own"); require(to != address(0), "TRC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } function isContract(address _addr) private view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } function _checkOnTRC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!isContract(to)) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( ITRC721Receiver(to).onTRC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("TRC721: transfer to non TRC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _TRC721_RECEIVED); } } function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract TRC721Metadata is Context, TRC165, TRC721, ITRC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_TRC721_METADATA = 0x5b5e139f; constructor (string memory name, string memory symbol, string memory baseURI) public { _name = name; _symbol = symbol; _baseURI = baseURI; _registerInterface(_INTERFACE_ID_TRC721_METADATA); } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "TRC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require(_exists(tokenId), "TRC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _setBaseURI(string memory baseURI) internal { _baseURI = baseURI; } function baseURI() external view returns (string memory) { return _baseURI; } function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract TRC721MetadataMintable is TRC721, TRC721Metadata, MinterRole { function updateBaseURI(string memory baseURI) public onlyMinter returns(bool){ _setBaseURI(baseURI); return true; } function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; } function updateTokenURI(uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _setTokenURI(tokenId, tokenURI); return true; } } contract TRC721Mintable is TRC721, MinterRole { function mint(address to, uint256 tokenId) public onlyMinter returns (bool) { _mint(to, tokenId); return true; } function safeMint(address to, uint256 tokenId) public onlyMinter returns (bool) { _safeMint(to, tokenId); return true; } function safeMint(address to, uint256 tokenId, bytes memory _data) public onlyMinter returns (bool) { _safeMint(to, tokenId, _data); return true; } } contract ITRC721Enumerable is ITRC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } contract TRC721Enumerable is Context, TRC165, TRC721, ITRC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_TRC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to TRC721Enumerable via TRC165 _registerInterface(_INTERFACE_ID_TRC721_ENUMERABLE); } function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "TRC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function totalSupply() public view returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "TRC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } _ownedTokens[from].length--; } function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; 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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } contract TRC721Token is TRC721, TRC721Enumerable, TRC721MetadataMintable { constructor() public TRC721Metadata("Brutus Gallery", "BRGY", "https://mintearte.tk/") { } }
Equals to `bytes4(keccak256("onTRC721Received(address,address,uint256,bytes)"))` which can be also obtained as `ITRC721Receiver(0).onTRC721Received.selector` NOTE: TRC721 uses 0x150b7a02, TRC721 uses 0x5175f878. Mapping from token ID to owner Mapping from token ID to approved address Mapping from owner to number of owned token Mapping from owner to operator approvals
contract TRC721 is Context, TRC165, ITRC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; bytes4 private constant _TRC721_RECEIVED = 0x5175f878; mapping (uint256 => address) private _tokenOwner; mapping (uint256 => address) private _tokenApprovals; mapping (address => Counters.Counter) private _ownedTokensCount; mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_TRC721 = 0x80ac58cd; constructor () public { _registerInterface(_INTERFACE_ID_TRC721); } function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "TRC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "TRC721: owner query for nonexistent token"); return owner; } function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "TRC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "TRC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "TRC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "TRC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "TRC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "TRC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnTRC721Received(from, to, tokenId, _data), "TRC721: transfer to non TRC721Receiver implementer"); } function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "TRC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnTRC721Received(address(0), to, tokenId, _data), "TRC721: transfer to non TRC721Receiver implementer"); } function _mint(address to, uint256 tokenId) internal { require(to != address(0), "TRC721: mint to the zero address"); require(!_exists(tokenId), "TRC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "TRC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "TRC721: transfer of token that is not own"); require(to != address(0), "TRC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } function isContract(address _addr) private view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } function isContract(address _addr) private view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } function _checkOnTRC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!isContract(to)) { return true; } ITRC721Receiver(to).onTRC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("TRC721: transfer to non TRC721Receiver implementer"); } bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _TRC721_RECEIVED); } } function _checkOnTRC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!isContract(to)) { return true; } ITRC721Receiver(to).onTRC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("TRC721: transfer to non TRC721Receiver implementer"); } bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _TRC721_RECEIVED); } } (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( function _checkOnTRC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!isContract(to)) { return true; } ITRC721Receiver(to).onTRC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("TRC721: transfer to non TRC721Receiver implementer"); } bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _TRC721_RECEIVED); } } function _checkOnTRC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!isContract(to)) { return true; } ITRC721Receiver(to).onTRC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("TRC721: transfer to non TRC721Receiver implementer"); } bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _TRC721_RECEIVED); } } function _checkOnTRC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!isContract(to)) { return true; } ITRC721Receiver(to).onTRC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("TRC721: transfer to non TRC721Receiver implementer"); } bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _TRC721_RECEIVED); } } } else { } else { function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
12,958,778
[ 1, 8867, 358, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 4349, 39, 27, 5340, 8872, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 2225, 3719, 68, 1492, 848, 506, 2546, 12700, 487, 1375, 1285, 11529, 27, 5340, 12952, 12, 20, 2934, 265, 4349, 39, 27, 5340, 8872, 18, 9663, 68, 5219, 30, 4235, 39, 27, 5340, 4692, 374, 92, 23014, 70, 27, 69, 3103, 16, 4235, 39, 27, 5340, 4692, 374, 92, 25, 4033, 25, 74, 28, 8285, 18, 9408, 628, 1147, 1599, 358, 3410, 9408, 628, 1147, 1599, 358, 20412, 1758, 9408, 628, 3410, 358, 1300, 434, 16199, 1147, 9408, 628, 3410, 358, 3726, 6617, 4524, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4235, 39, 27, 5340, 353, 1772, 16, 4235, 39, 28275, 16, 467, 4349, 39, 27, 5340, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 4349, 39, 27, 5340, 67, 27086, 20764, 273, 374, 92, 25, 4033, 25, 74, 28, 8285, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 5541, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 261, 2867, 516, 9354, 87, 18, 4789, 13, 3238, 389, 995, 329, 5157, 1380, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 4349, 39, 27, 5340, 273, 374, 92, 3672, 1077, 8204, 4315, 31, 203, 203, 565, 3885, 1832, 1071, 288, 203, 3639, 389, 4861, 1358, 24899, 18865, 67, 734, 67, 4349, 39, 27, 5340, 1769, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 4349, 39, 27, 5340, 30, 11013, 843, 364, 326, 3634, 1758, 8863, 203, 203, 3639, 327, 389, 995, 329, 5157, 1380, 63, 8443, 8009, 2972, 5621, 203, 565, 289, 203, 203, 565, 445, 3410, 951, 12, 11890, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./interfaces/AggregatorV3Interface.sol"; import "./interfaces/LinkTokenInterface.sol"; import "./interfaces/KeeperCompatibleInterface.sol"; import "./interfaces/KeeperRegistryInterface.sol"; import "./interfaces/TypeAndVersionInterface.sol"; import "./vendor/SafeMathChainlink.sol"; import "./vendor/Address.sol"; import "./vendor/Pausable.sol"; import "./vendor/ReentrancyGuard.sol"; import "./vendor/SignedSafeMath.sol"; import "./vendor/SafeMath96.sol"; import "./KeeperBase.sol"; import "./ConfirmedOwner.sol"; /** * @notice Registry for adding work for Chainlink Keepers to perform on client * contracts. Clients must support the Upkeep interface. */ contract KeeperRegistry1_1 is TypeAndVersionInterface, ConfirmedOwner, KeeperBase, ReentrancyGuard, Pausable, KeeperRegistryExecutableInterface { using Address for address; using SafeMathChainlink for uint256; using SafeMath96 for uint96; using SignedSafeMath for int256; address private constant ZERO_ADDRESS = address(0); address private constant IGNORE_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; bytes4 private constant CHECK_SELECTOR = KeeperCompatibleInterface.checkUpkeep.selector; bytes4 private constant PERFORM_SELECTOR = KeeperCompatibleInterface.performUpkeep.selector; uint256 private constant CALL_GAS_MAX = 5_000_000; uint256 private constant CALL_GAS_MIN = 2_300; uint256 private constant CANCELATION_DELAY = 50; uint256 private constant CUSHION = 5_000; uint256 private constant REGISTRY_GAS_OVERHEAD = 80_000; uint256 private constant PPB_BASE = 1_000_000_000; uint64 private constant UINT64_MAX = 2**64 - 1; uint96 private constant LINK_TOTAL_SUPPLY = 1e27; uint256 private s_upkeepCount; uint256[] private s_canceledUpkeepList; address[] private s_keeperList; mapping(uint256 => Upkeep) private s_upkeep; mapping(address => KeeperInfo) private s_keeperInfo; mapping(address => address) private s_proposedPayee; mapping(uint256 => bytes) private s_checkData; Config private s_config; uint256 private s_fallbackGasPrice; // not in config object for gas savings uint256 private s_fallbackLinkPrice; // not in config object for gas savings uint256 private s_expectedLinkBalance; LinkTokenInterface public immutable LINK; AggregatorV3Interface public immutable LINK_ETH_FEED; AggregatorV3Interface public immutable FAST_GAS_FEED; address private s_registrar; /** * @notice versions: * - KeeperRegistry 1.1.0: added flatFeeMicroLink * - KeeperRegistry 1.0.0: initial release */ string public constant override typeAndVersion = "KeeperRegistry 1.1.0"; struct Upkeep { address target; uint32 executeGas; uint96 balance; address admin; uint64 maxValidBlocknumber; address lastKeeper; } struct KeeperInfo { address payee; uint96 balance; bool active; } struct Config { uint32 paymentPremiumPPB; uint32 flatFeeMicroLink; // min 0.000001 LINK, max 4294 LINK uint24 blockCountPerTurn; uint32 checkGasLimit; uint24 stalenessSeconds; uint16 gasCeilingMultiplier; } struct PerformParams { address from; uint256 id; bytes performData; uint256 maxLinkPayment; uint256 gasLimit; uint256 adjustedGasWei; uint256 linkEth; } event UpkeepRegistered(uint256 indexed id, uint32 executeGas, address admin); event UpkeepPerformed( uint256 indexed id, bool indexed success, address indexed from, uint96 payment, bytes performData ); event UpkeepCanceled(uint256 indexed id, uint64 indexed atBlockHeight); event FundsAdded(uint256 indexed id, address indexed from, uint96 amount); event FundsWithdrawn(uint256 indexed id, uint256 amount, address to); event ConfigSet( uint32 paymentPremiumPPB, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ); event FlatFeeSet(uint32 flatFeeMicroLink); event KeepersUpdated(address[] keepers, address[] payees); event PaymentWithdrawn(address indexed keeper, uint256 indexed amount, address indexed to, address payee); event PayeeshipTransferRequested(address indexed keeper, address indexed from, address indexed to); event PayeeshipTransferred(address indexed keeper, address indexed from, address indexed to); event RegistrarChanged(address indexed from, address indexed to); /** * @param link address of the LINK Token * @param linkEthFeed address of the LINK/ETH price feed * @param fastGasFeed address of the Fast Gas price feed * @param paymentPremiumPPB payment premium rate oracles receive on top of * being reimbursed for gas, measured in parts per billion * @param flatFeeMicroLink flat fee paid to oracles for performing upkeeps, * priced in MicroLink; can be used in conjunction with or independently of * paymentPremiumPPB * @param blockCountPerTurn number of blocks each oracle has during their turn to * perform upkeep before it will be the next keeper's turn to submit * @param checkGasLimit gas limit when checking for upkeep * @param stalenessSeconds number of seconds that is allowed for feed data to * be stale before switching to the fallback pricing * @param gasCeilingMultiplier multiplier to apply to the fast gas feed price * when calculating the payment ceiling for keepers * @param fallbackGasPrice gas price used if the gas price feed is stale * @param fallbackLinkPrice LINK price used if the LINK price feed is stale */ constructor( address link, address linkEthFeed, address fastGasFeed, uint32 paymentPremiumPPB, uint32 flatFeeMicroLink, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ) ConfirmedOwner(msg.sender) { LINK = LinkTokenInterface(link); LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed); FAST_GAS_FEED = AggregatorV3Interface(fastGasFeed); setConfig( paymentPremiumPPB, flatFeeMicroLink, blockCountPerTurn, checkGasLimit, stalenessSeconds, gasCeilingMultiplier, fallbackGasPrice, fallbackLinkPrice ); } // ACTIONS /** * @notice adds a new upkeep * @param target address to perform upkeep on * @param gasLimit amount of gas to provide the target contract when * performing upkeep * @param admin address to cancel upkeep and withdraw remaining funds * @param checkData data passed to the contract when checking for upkeep */ function registerUpkeep( address target, uint32 gasLimit, address admin, bytes calldata checkData ) external override onlyOwnerOrRegistrar returns (uint256 id) { require(target.isContract(), "target is not a contract"); require(gasLimit >= CALL_GAS_MIN, "min gas is 2300"); require(gasLimit <= CALL_GAS_MAX, "max gas is 5000000"); id = s_upkeepCount; s_upkeep[id] = Upkeep({ target: target, executeGas: gasLimit, balance: 0, admin: admin, maxValidBlocknumber: UINT64_MAX, lastKeeper: address(0) }); s_checkData[id] = checkData; s_upkeepCount++; emit UpkeepRegistered(id, gasLimit, admin); return id; } /** * @notice simulated by keepers via eth_call to see if the upkeep needs to be * performed. If upkeep is needed, the call then simulates performUpkeep * to make sure it succeeds. Finally, it returns the success status along with * payment information and the perform data payload. * @param id identifier of the upkeep to check * @param from the address to simulate performing the upkeep from */ function checkUpkeep(uint256 id, address from) external override whenNotPaused cannotExecute returns ( bytes memory performData, uint256 maxLinkPayment, uint256 gasLimit, uint256 adjustedGasWei, uint256 linkEth ) { Upkeep memory upkeep = s_upkeep[id]; bytes memory callData = abi.encodeWithSelector(CHECK_SELECTOR, s_checkData[id]); (bool success, bytes memory result) = upkeep.target.call{gas: s_config.checkGasLimit}(callData); if (!success) { string memory upkeepRevertReason = getRevertMsg(result); string memory reason = string(abi.encodePacked("call to check target failed: ", upkeepRevertReason)); revert(reason); } (success, performData) = abi.decode(result, (bool, bytes)); require(success, "upkeep not needed"); PerformParams memory params = generatePerformParams(from, id, performData, false); prePerformUpkeep(upkeep, params.from, params.maxLinkPayment); return (performData, params.maxLinkPayment, params.gasLimit, params.adjustedGasWei, params.linkEth); } /** * @notice executes the upkeep with the perform data returned from * checkUpkeep, validates the keeper's permissions, and pays the keeper. * @param id identifier of the upkeep to execute the data with. * @param performData calldata parameter to be passed to the target upkeep. */ function performUpkeep(uint256 id, bytes calldata performData) external override returns (bool success) { return performUpkeepWithParams(generatePerformParams(msg.sender, id, performData, true)); } /** * @notice prevent an upkeep from being performed in the future * @param id upkeep to be canceled */ function cancelUpkeep(uint256 id) external override { uint64 maxValid = s_upkeep[id].maxValidBlocknumber; bool notCanceled = maxValid == UINT64_MAX; bool isOwner = msg.sender == owner(); require(notCanceled || (isOwner && maxValid > block.number), "too late to cancel upkeep"); require(isOwner || msg.sender == s_upkeep[id].admin, "only owner or admin"); uint256 height = block.number; if (!isOwner) { height = height.add(CANCELATION_DELAY); } s_upkeep[id].maxValidBlocknumber = uint64(height); if (notCanceled) { s_canceledUpkeepList.push(id); } emit UpkeepCanceled(id, uint64(height)); } /** * @notice adds LINK funding for an upkeep by transferring from the sender's * LINK balance * @param id upkeep to fund * @param amount number of LINK to transfer */ function addFunds(uint256 id, uint96 amount) external override { require(s_upkeep[id].maxValidBlocknumber == UINT64_MAX, "upkeep must be active"); s_upkeep[id].balance = s_upkeep[id].balance.add(amount); s_expectedLinkBalance = s_expectedLinkBalance.add(amount); LINK.transferFrom(msg.sender, address(this), amount); emit FundsAdded(id, msg.sender, amount); } /** * @notice uses LINK's transferAndCall to LINK and add funding to an upkeep * @dev safe to cast uint256 to uint96 as total LINK supply is under UINT96MAX * @param sender the account which transferred the funds * @param amount number of LINK transfer */ function onTokenTransfer( address sender, uint256 amount, bytes calldata data ) external { require(msg.sender == address(LINK), "only callable through LINK"); require(data.length == 32, "data must be 32 bytes"); uint256 id = abi.decode(data, (uint256)); require(s_upkeep[id].maxValidBlocknumber == UINT64_MAX, "upkeep must be active"); s_upkeep[id].balance = s_upkeep[id].balance.add(uint96(amount)); s_expectedLinkBalance = s_expectedLinkBalance.add(amount); emit FundsAdded(id, sender, uint96(amount)); } /** * @notice removes funding from a canceled upkeep * @param id upkeep to withdraw funds from * @param to destination address for sending remaining funds */ function withdrawFunds(uint256 id, address to) external validateRecipient(to) { require(s_upkeep[id].admin == msg.sender, "only callable by admin"); require(s_upkeep[id].maxValidBlocknumber <= block.number, "upkeep must be canceled"); uint256 amount = s_upkeep[id].balance; s_upkeep[id].balance = 0; s_expectedLinkBalance = s_expectedLinkBalance.sub(amount); emit FundsWithdrawn(id, amount, to); LINK.transfer(to, amount); } /** * @notice recovers LINK funds improperly transferred to the registry * @dev In principle this function’s execution cost could exceed block * gas limit. However, in our anticipated deployment, the number of upkeeps and * keepers will be low enough to avoid this problem. */ function recoverFunds() external onlyOwner { uint256 total = LINK.balanceOf(address(this)); LINK.transfer(msg.sender, total.sub(s_expectedLinkBalance)); } /** * @notice withdraws a keeper's payment, callable only by the keeper's payee * @param from keeper address * @param to address to send the payment to */ function withdrawPayment(address from, address to) external validateRecipient(to) { KeeperInfo memory keeper = s_keeperInfo[from]; require(keeper.payee == msg.sender, "only callable by payee"); s_keeperInfo[from].balance = 0; s_expectedLinkBalance = s_expectedLinkBalance.sub(keeper.balance); emit PaymentWithdrawn(from, keeper.balance, to, msg.sender); LINK.transfer(to, keeper.balance); } /** * @notice proposes the safe transfer of a keeper's payee to another address * @param keeper address of the keeper to transfer payee role * @param proposed address to nominate for next payeeship */ function transferPayeeship(address keeper, address proposed) external { require(s_keeperInfo[keeper].payee == msg.sender, "only callable by payee"); require(proposed != msg.sender, "cannot transfer to self"); if (s_proposedPayee[keeper] != proposed) { s_proposedPayee[keeper] = proposed; emit PayeeshipTransferRequested(keeper, msg.sender, proposed); } } /** * @notice accepts the safe transfer of payee role for a keeper * @param keeper address to accept the payee role for */ function acceptPayeeship(address keeper) external { require(s_proposedPayee[keeper] == msg.sender, "only callable by proposed payee"); address past = s_keeperInfo[keeper].payee; s_keeperInfo[keeper].payee = msg.sender; s_proposedPayee[keeper] = ZERO_ADDRESS; emit PayeeshipTransferred(keeper, past, msg.sender); } /** * @notice signals to keepers that they should not perform upkeeps until the * contract has been unpaused */ function pause() external onlyOwner { _pause(); } /** * @notice signals to keepers that they can perform upkeeps once again after * having been paused */ function unpause() external onlyOwner { _unpause(); } // SETTERS /** * @notice updates the configuration of the registry * @param paymentPremiumPPB payment premium rate oracles receive on top of * being reimbursed for gas, measured in parts per billion * @param flatFeeMicroLink flat fee paid to oracles for performing upkeeps * @param blockCountPerTurn number of blocks an oracle should wait before * checking for upkeep * @param checkGasLimit gas limit when checking for upkeep * @param stalenessSeconds number of seconds that is allowed for feed data to * be stale before switching to the fallback pricing * @param fallbackGasPrice gas price used if the gas price feed is stale * @param fallbackLinkPrice LINK price used if the LINK price feed is stale */ function setConfig( uint32 paymentPremiumPPB, uint32 flatFeeMicroLink, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ) public onlyOwner { s_config = Config({ paymentPremiumPPB: paymentPremiumPPB, flatFeeMicroLink: flatFeeMicroLink, blockCountPerTurn: blockCountPerTurn, checkGasLimit: checkGasLimit, stalenessSeconds: stalenessSeconds, gasCeilingMultiplier: gasCeilingMultiplier }); s_fallbackGasPrice = fallbackGasPrice; s_fallbackLinkPrice = fallbackLinkPrice; emit ConfigSet( paymentPremiumPPB, blockCountPerTurn, checkGasLimit, stalenessSeconds, gasCeilingMultiplier, fallbackGasPrice, fallbackLinkPrice ); emit FlatFeeSet(flatFeeMicroLink); } /** * @notice update the list of keepers allowed to perform upkeep * @param keepers list of addresses allowed to perform upkeep * @param payees addresses corresponding to keepers who are allowed to * move payments which have been accrued */ function setKeepers(address[] calldata keepers, address[] calldata payees) external onlyOwner { require(keepers.length == payees.length, "address lists not the same length"); require(keepers.length >= 2, "not enough keepers"); for (uint256 i = 0; i < s_keeperList.length; i++) { address keeper = s_keeperList[i]; s_keeperInfo[keeper].active = false; } for (uint256 i = 0; i < keepers.length; i++) { address keeper = keepers[i]; KeeperInfo storage s_keeper = s_keeperInfo[keeper]; address oldPayee = s_keeper.payee; address newPayee = payees[i]; require(newPayee != address(0), "cannot set payee to the zero address"); require(oldPayee == ZERO_ADDRESS || oldPayee == newPayee || newPayee == IGNORE_ADDRESS, "cannot change payee"); require(!s_keeper.active, "cannot add keeper twice"); s_keeper.active = true; if (newPayee != IGNORE_ADDRESS) { s_keeper.payee = newPayee; } } s_keeperList = keepers; emit KeepersUpdated(keepers, payees); } /** * @notice update registrar * @param registrar new registrar */ function setRegistrar(address registrar) external onlyOwnerOrRegistrar { address previous = s_registrar; require(registrar != previous, "Same registrar"); s_registrar = registrar; emit RegistrarChanged(previous, registrar); } // GETTERS /** * @notice read all of the details about an upkeep */ function getUpkeep(uint256 id) external view override returns ( address target, uint32 executeGas, bytes memory checkData, uint96 balance, address lastKeeper, address admin, uint64 maxValidBlocknumber ) { Upkeep memory reg = s_upkeep[id]; return ( reg.target, reg.executeGas, s_checkData[id], reg.balance, reg.lastKeeper, reg.admin, reg.maxValidBlocknumber ); } /** * @notice read the total number of upkeep's registered */ function getUpkeepCount() external view override returns (uint256) { return s_upkeepCount; } /** * @notice read the current list canceled upkeep IDs */ function getCanceledUpkeepList() external view override returns (uint256[] memory) { return s_canceledUpkeepList; } /** * @notice read the current list of addresses allowed to perform upkeep */ function getKeeperList() external view override returns (address[] memory) { return s_keeperList; } /** * @notice read the current registrar */ function getRegistrar() external view returns (address) { return s_registrar; } /** * @notice read the current info about any keeper address */ function getKeeperInfo(address query) external view override returns ( address payee, bool active, uint96 balance ) { KeeperInfo memory keeper = s_keeperInfo[query]; return (keeper.payee, keeper.active, keeper.balance); } /** * @notice read the current configuration of the registry */ function getConfig() external view override returns ( uint32 paymentPremiumPPB, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, uint256 fallbackGasPrice, uint256 fallbackLinkPrice ) { Config memory config = s_config; return ( config.paymentPremiumPPB, config.blockCountPerTurn, config.checkGasLimit, config.stalenessSeconds, config.gasCeilingMultiplier, s_fallbackGasPrice, s_fallbackLinkPrice ); } /** * @notice getFlatFee gets the flat rate fee charged to customers when performing upkeep, * in units of of micro LINK */ function getFlatFee() external view returns (uint32) { return s_config.flatFeeMicroLink; } /** * @notice calculates the minimum balance required for an upkeep to remain eligible */ function getMinBalanceForUpkeep(uint256 id) external view returns (uint96 minBalance) { return getMaxPaymentForGas(s_upkeep[id].executeGas); } /** * @notice calculates the maximum payment for a given gas limit */ function getMaxPaymentForGas(uint256 gasLimit) public view returns (uint96 maxPayment) { (uint256 gasWei, uint256 linkEth) = getFeedData(); uint256 adjustedGasWei = adjustGasPrice(gasWei, false); return calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth); } // PRIVATE /** * @dev retrieves feed data for fast gas/eth and link/eth prices. if the feed * data is stale it uses the configured fallback price. Once a price is picked * for gas it takes the min of gas price in the transaction or the fast gas * price in order to reduce costs for the upkeep clients. */ function getFeedData() private view returns (uint256 gasWei, uint256 linkEth) { uint32 stalenessSeconds = s_config.stalenessSeconds; bool staleFallback = stalenessSeconds > 0; uint256 timestamp; int256 feedValue; (, feedValue, , timestamp, ) = FAST_GAS_FEED.latestRoundData(); if ((staleFallback && stalenessSeconds < block.timestamp - timestamp) || feedValue <= 0) { gasWei = s_fallbackGasPrice; } else { gasWei = uint256(feedValue); } (, feedValue, , timestamp, ) = LINK_ETH_FEED.latestRoundData(); if ((staleFallback && stalenessSeconds < block.timestamp - timestamp) || feedValue <= 0) { linkEth = s_fallbackLinkPrice; } else { linkEth = uint256(feedValue); } return (gasWei, linkEth); } /** * @dev calculates LINK paid for gas spent plus a configure premium percentage */ function calculatePaymentAmount( uint256 gasLimit, uint256 gasWei, uint256 linkEth ) private view returns (uint96 payment) { Config memory config = s_config; uint256 weiForGas = gasWei.mul(gasLimit.add(REGISTRY_GAS_OVERHEAD)); uint256 premium = PPB_BASE.add(config.paymentPremiumPPB); uint256 total = weiForGas.mul(1e9).mul(premium).div(linkEth).add(uint256(config.flatFeeMicroLink).mul(1e12)); require(total <= LINK_TOTAL_SUPPLY, "payment greater than all LINK"); return uint96(total); // LINK_TOTAL_SUPPLY < UINT96_MAX } /** * @dev calls target address with exactly gasAmount gas and data as calldata * or reverts if at least gasAmount gas is not available */ function callWithExactGas( uint256 gasAmount, address target, bytes memory data ) private returns (bool success) { assembly { let g := gas() // Compute g -= CUSHION and check for underflow if lt(g, CUSHION) { revert(0, 0) } g := sub(g, CUSHION) // if g - g//64 <= gasAmount, revert // (we subtract g//64 because of EIP-150) if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } // solidity calls check that a contract actually exists at the destination, so we do the same if iszero(extcodesize(target)) { revert(0, 0) } // call and return whether we succeeded. ignore return data success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0) } return success; } /** * @dev calls the Upkeep target with the performData param passed in by the * keeper and the exact gas required by the Upkeep */ function performUpkeepWithParams(PerformParams memory params) private nonReentrant validUpkeep(params.id) returns (bool success) { Upkeep memory upkeep = s_upkeep[params.id]; prePerformUpkeep(upkeep, params.from, params.maxLinkPayment); uint256 gasUsed = gasleft(); bytes memory callData = abi.encodeWithSelector(PERFORM_SELECTOR, params.performData); success = callWithExactGas(params.gasLimit, upkeep.target, callData); gasUsed = gasUsed - gasleft(); uint96 payment = calculatePaymentAmount(gasUsed, params.adjustedGasWei, params.linkEth); uint96 newUpkeepBalance = s_upkeep[params.id].balance.sub(payment); s_upkeep[params.id].balance = newUpkeepBalance; s_upkeep[params.id].lastKeeper = params.from; uint96 newKeeperBalance = s_keeperInfo[params.from].balance.add(payment); s_keeperInfo[params.from].balance = newKeeperBalance; emit UpkeepPerformed(params.id, success, params.from, payment, params.performData); return success; } /** * @dev ensures a upkeep is valid */ function validateUpkeep(uint256 id) private view { require(s_upkeep[id].maxValidBlocknumber > block.number, "invalid upkeep id"); } /** * @dev ensures all required checks are passed before an upkeep is performed */ function prePerformUpkeep( Upkeep memory upkeep, address from, uint256 maxLinkPayment ) private view { require(s_keeperInfo[from].active, "only active keepers"); require(upkeep.balance >= maxLinkPayment, "insufficient funds"); require(upkeep.lastKeeper != from, "keepers must take turns"); } /** * @dev adjusts the gas price to min(ceiling, tx.gasprice) or just uses the ceiling if tx.gasprice is disabled */ function adjustGasPrice(uint256 gasWei, bool useTxGasPrice) private view returns (uint256 adjustedPrice) { adjustedPrice = gasWei.mul(s_config.gasCeilingMultiplier); if (useTxGasPrice && tx.gasprice < adjustedPrice) { adjustedPrice = tx.gasprice; } } /** * @dev generates a PerformParams struct for use in performUpkeepWithParams() */ function generatePerformParams( address from, uint256 id, bytes memory performData, bool useTxGasPrice ) private view returns (PerformParams memory) { uint256 gasLimit = s_upkeep[id].executeGas; (uint256 gasWei, uint256 linkEth) = getFeedData(); uint256 adjustedGasWei = adjustGasPrice(gasWei, useTxGasPrice); uint96 maxLinkPayment = calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth); return PerformParams({ from: from, id: id, performData: performData, maxLinkPayment: maxLinkPayment, gasLimit: gasLimit, adjustedGasWei: adjustedGasWei, linkEth: linkEth }); } /** * @dev extracts a revert reason from a call result payload */ function getRevertMsg(bytes memory _payload) private pure returns (string memory) { if (_payload.length < 68) return "transaction reverted silently"; assembly { _payload := add(_payload, 0x04) } return abi.decode(_payload, (string)); } // MODIFIERS /** * @dev ensures a upkeep is valid */ modifier validUpkeep(uint256 id) { validateUpkeep(id); _; } /** * @dev ensures that burns don't accidentally happen by sending to the zero * address */ modifier validateRecipient(address to) { require(to != address(0), "cannot send to zero address"); _; } /** * @dev Reverts if called by anyone other than the contract owner or registrar. */ modifier onlyOwnerOrRegistrar() { require(msg.sender == owner() || msg.sender == s_registrar, "Only callable by owner or registrar"); _; } }
* @dev calculates LINK paid for gas spent plus a configure premium percentage/
function calculatePaymentAmount( uint256 gasLimit, uint256 gasWei, uint256 linkEth ) private view returns (uint96 payment) { Config memory config = s_config; uint256 weiForGas = gasWei.mul(gasLimit.add(REGISTRY_GAS_OVERHEAD)); uint256 premium = PPB_BASE.add(config.paymentPremiumPPB); uint256 total = weiForGas.mul(1e9).mul(premium).div(linkEth).add(uint256(config.flatFeeMicroLink).mul(1e12)); require(total <= LINK_TOTAL_SUPPLY, "payment greater than all LINK"); }
12,571,862
[ 1, 12780, 815, 22926, 30591, 364, 16189, 26515, 8737, 279, 5068, 23020, 5077, 11622, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4604, 6032, 6275, 12, 203, 565, 2254, 5034, 16189, 3039, 16, 203, 565, 2254, 5034, 16189, 3218, 77, 16, 203, 565, 2254, 5034, 1692, 41, 451, 203, 225, 262, 3238, 1476, 1135, 261, 11890, 10525, 5184, 13, 288, 203, 565, 1903, 3778, 642, 273, 272, 67, 1425, 31, 203, 565, 2254, 5034, 732, 77, 1290, 27998, 273, 16189, 3218, 77, 18, 16411, 12, 31604, 3039, 18, 1289, 12, 5937, 25042, 67, 43, 3033, 67, 12959, 12458, 10019, 203, 565, 2254, 5034, 23020, 5077, 273, 453, 20724, 67, 8369, 18, 1289, 12, 1425, 18, 9261, 23890, 5077, 6584, 38, 1769, 203, 565, 2254, 5034, 2078, 273, 732, 77, 1290, 27998, 18, 16411, 12, 21, 73, 29, 2934, 16411, 12, 1484, 81, 5077, 2934, 2892, 12, 1232, 41, 451, 2934, 1289, 12, 11890, 5034, 12, 1425, 18, 15401, 14667, 13617, 2098, 2934, 16411, 12, 21, 73, 2138, 10019, 203, 565, 2583, 12, 4963, 1648, 22926, 67, 28624, 67, 13272, 23893, 16, 315, 9261, 6802, 2353, 777, 22926, 8863, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/IRelayRecipient.sol pragma solidity ^0.5.0; /* * @dev Interface for a contract that will be called via the GSN from RelayHub. */ contract IRelayRecipient { /** * @dev Returns the address of the RelayHub instance this recipient interacts with. */ function getHubAddr() public view returns (address); function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 maxPossibleCharge ) external view returns (uint256, bytes memory); function preRelayedCall(bytes calldata context) external returns (bytes32); function postRelayedCall(bytes calldata context, bool success, uint actualCharge, bytes32 preRetVal) external; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/bouncers/GSNBouncerBase.sol pragma solidity ^0.5.0; /* * @dev Base contract used to implement GSNBouncers. * * > This contract does not perform all required tasks to implement a GSN * recipient contract: end users should use `GSNRecipient` instead. */ contract GSNBouncerBase is IRelayRecipient { uint256 constant private RELAYED_CALL_ACCEPTED = 0; uint256 constant private RELAYED_CALL_REJECTED = 11; // How much gas is forwarded to postRelayedCall uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000; // Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the // internal hook. /** * @dev See `IRelayRecipient.preRelayedCall`. * * This function should not be overriden directly, use `_preRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function preRelayedCall(bytes calldata context) external returns (bytes32) { require(msg.sender == getHubAddr(), "GSNBouncerBase: caller is not RelayHub"); return _preRelayedCall(context); } /** * @dev See `IRelayRecipient.postRelayedCall`. * * This function should not be overriden directly, use `_postRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external { require(msg.sender == getHubAddr(), "GSNBouncerBase: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } /** * @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract * will be charged a fee by RelayHub */ function _approveRelayedCall() internal pure returns (uint256, bytes memory) { return _approveRelayedCall(""); } /** * @dev See `GSNBouncerBase._approveRelayedCall`. * * This overload forwards `context` to _preRelayedCall and _postRelayedCall. */ function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); } /** * @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged. */ function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_REJECTED + errorCode, ""); } // Empty hooks for pre and post relayed call: users only have to define these if they actually use them. function _preRelayedCall(bytes memory) internal returns (bytes32) { // solhint-disable-previous-line no-empty-blocks } function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal { // solhint-disable-previous-line no-empty-blocks } /* * @dev Calculates how much RelaHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's * `serviceFee`. */ function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) { // The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be // charged for 1.4 times the spent amount. return (gas * gasPrice * (100 + serviceFee)) / 100; } } // File: @openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.2; /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/bouncers/GSNBouncerSignature.sol pragma solidity ^0.5.0; contract GSNBouncerSignature is Initializable, GSNBouncerBase { using ECDSA for bytes32; // We use a random storage slot to allow proxy contracts to enable GSN support in an upgrade without changing their // storage layout. This value is calculated as: keccak256('gsn.bouncer.signature.trustedSigner'), minus 1. bytes32 constant private TRUSTED_SIGNER_STORAGE_SLOT = 0xe7b237a4017a399d277819456dce32c2356236bbc518a6d84a9a8d1cfdf1e9c5; enum GSNBouncerSignatureErrorCodes { INVALID_SIGNER } function initialize(address trustedSigner) public initializer { _setTrustedSigner(trustedSigner); } function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 ) external view returns (uint256, bytes memory) { bytes memory blob = abi.encodePacked( relay, from, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, // Prevents replays on RelayHub getHubAddr(), // Prevents replays in multiple RelayHubs address(this) // Prevents replays in multiple recipients ); if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) == _getTrustedSigner()) { return _approveRelayedCall(); } else { return _rejectRelayedCall(uint256(GSNBouncerSignatureErrorCodes.INVALID_SIGNER)); } } function _getTrustedSigner() private view returns (address trustedSigner) { bytes32 slot = TRUSTED_SIGNER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { trustedSigner := sload(slot) } } function _setTrustedSigner(address trustedSigner) private { bytes32 slot = TRUSTED_SIGNER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, trustedSigner) } } } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they not 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, with should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/GSNContext.sol pragma solidity ^0.5.0; /* * @dev Enables GSN support on `Context` contracts by recognizing calls from * RelayHub and extracting the actual sender and call data from the received * calldata. * * > This contract does not perform all required tasks to implement a GSN * recipient contract: end users should use `GSNRecipient` instead. */ contract GSNContext is Initializable, Context { // We use a random storage slot to allow proxy contracts to enable GSN support in an upgrade without changing their // storage layout. This value is calculated as: keccak256('gsn.relayhub.address'), minus 1. bytes32 private constant RELAY_HUB_ADDRESS_STORAGE_SLOT = 0x06b7792c761dcc05af1761f0315ce8b01ac39c16cc934eb0b2f7a8e71414f262; event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); function initialize() public initializer { _upgradeRelayHub(0xD216153c06E857cD7f72665E0aF1d7D82172F494); } function _getRelayHub() internal view returns (address relayHub) { bytes32 slot = RELAY_HUB_ADDRESS_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { relayHub := sload(slot) } } function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _getRelayHub(); require(newRelayHub != address(0), "GSNContext: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNContext: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); bytes32 slot = RELAY_HUB_ADDRESS_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newRelayHub) } } // Overrides for Context's functions: when called from RelayHub, sender and // data require some pre-processing: the actual sender is stored at the end // of the call data, which in turns means it needs to be removed from it // when handling said data. function _msgSender() internal view returns (address) { if (msg.sender != _getRelayHub()) { return msg.sender; } else { return _getRelayedCallSender(); } } function _msgData() internal view returns (bytes memory) { if (msg.sender != _getRelayHub()) { return msg.data; } else { return _getRelayedCallData(); } } function _getRelayedCallSender() private pure returns (address result) { // We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array // is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing // so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would // require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 // bytes. This can always be done due to the 32-byte prefix. // The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the // easiest/most-efficient way to perform this operation. // These fields are not accessible from assembly bytes memory array = msg.data; uint256 index = msg.data.length; // solhint-disable-next-line no-inline-assembly assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function _getRelayedCallData() private pure returns (bytes memory) { // RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data, // we must strip the last 20 bytes (length of an address type) from it. uint256 actualDataLength = msg.data.length - 20; bytes memory actualData = new bytes(actualDataLength); for (uint256 i = 0; i < actualDataLength; ++i) { actualData[i] = msg.data[i]; } return actualData; } } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/IRelayHub.sol pragma solidity ^0.5.0; contract IRelayHub { // Relay management // Add stake to a relay and sets its unstakeDelay. // If the relay does not exist, it is created, and the caller // of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay // cannot be its own owner. // All Ether in this function call will be added to the relay's stake. // Its unstake delay will be assigned to unstakeDelay, but the new value must be greater or equal to the current one. // Emits a Staked event. function stake(address relayaddr, uint256 unstakeDelay) external payable; // Emited when a relay's stake or unstakeDelay are increased event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay); // Registers the caller as a relay. // The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA). // Emits a RelayAdded event. // This function can be called multiple times, emitting new RelayAdded events. Note that the received transactionFee // is not enforced by relayCall. function registerRelay(uint256 transactionFee, string memory url) public; // Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out RelayRemoved // events) lets a client discover the list of available relays. event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url); // Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. Can only be called by // the owner of the relay. After the relay's unstakeDelay has elapsed, unstake will be callable. // Emits a RelayRemoved event. function removeRelayByOwner(address relay) public; // Emitted when a relay is removed (deregistered). unstakeTime is the time when unstake will be callable. event RelayRemoved(address indexed relay, uint256 unstakeTime); // Deletes the relay from the system, and gives back its stake to the owner. Can only be called by the relay owner, // after unstakeDelay has elapsed since removeRelayByOwner was called. // Emits an Unstaked event. function unstake(address relay) public; // Emitted when a relay is unstaked for, including the returned stake. event Unstaked(address indexed relay, uint256 stake); // States a relay can be in enum RelayState { Unknown, // The relay is unknown to the system: it has never been staked for Staked, // The relay has been staked for, but it is not yet active Registered, // The relay has registered itself, and is active (can relay calls) Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake } // Returns a relay's status. Note that relays can be deleted when unstaked or penalized. function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state); // Balance management // Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only // be withdrawn by the contract itself, by callingn withdraw. // Emits a Deposited event. function depositFor(address target) public payable; // Emitted when depositFor is called, including the amount and account that was funded. event Deposited(address indexed recipient, address indexed from, uint256 amount); // Returns an account's deposits. These can be either a contnract's funds, or a relay owner's revenue. function balanceOf(address target) external view returns (uint256); // Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and // contracts can also use it to reduce their funding. // Emits a Withdrawn event. function withdraw(uint256 amount, address payable dest) public; // Emitted when an account withdraws funds from RelayHub. event Withdrawn(address indexed account, address indexed dest, uint256 amount); // Relaying // Check if the RelayHub will accept a relayed operation. Multiple things must be true for this to happen: // - all arguments must be signed for by the sender (from) // - the sender's nonce must be the current one // - the recipient must accept this transaction (via acceptRelayedCall) // Returns a PreconditionCheck value (OK when the transaction can be relayed), or a recipient-specific error code if // it returns one in acceptRelayedCall. function canRelay( address relay, address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData ) public view returns (uint256 status, bytes memory recipientContext); // Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values. enum PreconditionCheck { OK, // All checks passed, the call can be relayed WrongSignature, // The transaction to relay is not signed by requested sender WrongNonce, // The provided nonce has already been used by the sender AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code } // Relays a transaction. For this to suceed, multiple conditions must be met: // - canRelay must return PreconditionCheck.OK // - the sender must be a registered relay // - the transaction's gas price must be larger or equal to the one that was requested by the sender // - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the // recipient) use all gas available to them // - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is // spent) // // If all conditions are met, the call will be relayed and the recipient charged. preRelayedCall, the encoded // function and postRelayedCall will be called in order. // // Arguments: // - from: the client originating the request // - recipient: the target IRelayRecipient contract // - encodedFunction: the function call to relay, including data // - transactionFee: fee (%) the relay takes over actual gas cost // - gasPrice: gas price the client is willing to pay // - gasLimit: gas to forward when calling the encoded function // - nonce: client's nonce // - signature: client's signature over all previous params, plus the relay and RelayHub addresses // - approvalData: dapp-specific data forwared to acceptRelayedCall. This value is *not* verified by the Hub, but // it still can be used for e.g. a signature. // // Emits a TransactionRelayed event. function relayCall( address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData ) public; // Emitted when an attempt to relay a call failed. This can happen due to incorrect relayCall arguments, or the // recipient not accepting the relayed call. The actual relayed call was not executed, and the recipient not charged. // The reason field contains an error code: values 1-10 correspond to PreconditionCheck entries, and values over 10 // are custom recipient error codes returned from acceptRelayedCall. event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason); // Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be // indicated in the status field. // Useful when monitoring a relay's operation and relayed calls to a contract. // Charge is the ether value deducted from the recipient's balance, paid to the relay's owner. event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge); // Reason error codes for the TransactionRelayed event enum RelayCallStatus { OK, // The transaction was successfully relayed and execution successful - never included in the event RelayedCallFailed, // The transaction was relayed, but the relayed call failed PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing } // Returns how much gas should be forwarded to a call to relayCall, in order to relay a transaction that will spend // up to relayedCallStipend gas. function requiredGas(uint256 relayedCallStipend) public view returns (uint256); // Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee. function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256); // Relay penalization. Any account can penalize relays, removing them from the system immediately, and rewarding the // reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it // still loses half of its stake. // Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and // different data (gas price, gas limit, etc. may be different). The (unsigned) transaction data and signature for // both transactions must be provided. function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public; // Penalize a relay that sent a transaction that didn't target RelayHub's registerRelay or relayCall. function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public; event Penalized(address indexed relay, address sender, uint256 amount); function getNonce(address from) external view returns (uint256); } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/GSNRecipient.sol pragma solidity ^0.5.0; /* * @dev Base GSN recipient contract, adding the recipient interface and enabling * GSN support. Not all interface methods are implemented, derived contracts * must do so themselves. */ contract GSNRecipient is Initializable, IRelayRecipient, GSNContext, GSNBouncerBase { function initialize() public initializer { GSNContext.initialize(); } function getHubAddr() public view returns (address) { return _getRelayHub(); } // This function is view for future-proofing, it may require reading from // storage in the future. function relayHubVersion() public view returns (string memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return "1.0.0"; } function _withdrawDeposits(uint256 amount, address payable payee) internal { IRelayHub(_getRelayHub()).withdraw(amount, payee); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.2; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard is Initializable { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } uint256[50] private ______gap; } // File: @sablier/shared-contracts/compound/CarefulMath.sol pragma solidity ^0.5.8; /** * @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(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint 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(uint a, uint b) internal pure returns (MathError, uint) { 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(uint a, uint b) internal pure returns (MathError, uint) { 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(uint a, uint b) internal pure returns (MathError, uint) { uint 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(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // File: @sablier/shared-contracts/compound/Exponential.sol pragma solidity ^0.5.8; /** * @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 { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint 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(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint 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) pure internal returns (MathError, Exp memory) { (MathError error, uint 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) pure internal returns (MathError, Exp memory) { (MathError error, uint 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, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint 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, uint scalar) pure internal returns (MathError, uint) { (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, uint scalar, uint addend) pure internal returns (MathError, uint) { (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, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint 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(uint scalar, Exp memory divisor) pure internal 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, uint 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(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (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) pure internal returns (MathError, Exp memory) { (MathError err0, uint 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, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint 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(uint a, uint b) pure internal 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) pure internal 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) pure internal 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) pure internal returns (uint) { // 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) pure internal 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) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } // File: @sablier/shared-contracts/interfaces/ICERC20.sol pragma solidity 0.5.11; /** * @title CERC20 interface * @author Sablier * @dev See https://compound.finance/developers */ interface ICERC20 { function balanceOf(address who) external view returns (uint256); function isCToken() external view returns (bool); function approve(address spender, uint256 value) external returns (bool); function balanceOfUnderlying(address account) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // File: @sablier/shared-contracts/lifecycle/OwnableWithoutRenounce.sol pragma solidity 0.5.11; /** * @title OwnableWithoutRenounce * @author Sablier * @dev Fork of OpenZeppelin's Ownable contract, which provides basic authorization control, but with * the `renounceOwnership` function removed to avoid fat-finger errors. * We inherit from `Context` to keep this contract compatible with the Gas Station Network. * See https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/ownership/Ownable.sol * See https://forum.openzeppelin.com/t/contract-request-ownable-without-renounceownership/1400 * See https://docs.openzeppelin.com/contracts/2.x/gsn#_msg_sender_and_msg_data */ contract OwnableWithoutRenounce is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: @sablier/shared-contracts/lifecycle/PauserRoleWithoutRenounce.sol pragma solidity ^0.5.0; /** * @title PauserRoleWithoutRenounce * @author Sablier * @notice Fork of OpenZeppelin's PauserRole, but with the `renouncePauser` function removed to avoid fat-finger errors. * We inherit from `Context` to keep this contract compatible with the Gas Station Network. * See https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/access/roles/PauserRole.sol */ contract PauserRoleWithoutRenounce is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } // File: @sablier/shared-contracts/lifecycle/PausableWithoutRenounce.sol pragma solidity 0.5.11; /** * @title PausableWithoutRenounce * @author Sablier * @notice Fork of OpenZeppelin's Pausable, a contract module which allows children to implement an * emergency stop mechanism that can be triggered by an authorized account, but with the `renouncePauser` * function removed to avoid fat-finger errors. * We inherit from `Context` to keep this contract compatible with the Gas Station Network. * See https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/lifecycle/Pausable.sol * See https://docs.openzeppelin.com/contracts/2.x/gsn#_msg_sender_and_msg_data */ contract PausableWithoutRenounce is Initializable, Context, PauserRoleWithoutRenounce { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRoleWithoutRenounce.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @sablier/protocol/contracts/interfaces/ICTokenManager.sol pragma solidity 0.5.11; /** * @title CTokenManager Interface * @author Sablier */ interface ICTokenManager { /** * @notice Emits when the owner discards a cToken. */ event DiscardCToken(address indexed tokenAddress); /** * @notice Emits when the owner whitelists a cToken. */ event WhitelistCToken(address indexed tokenAddress); function whitelistCToken(address tokenAddress) external; function discardCToken(address tokenAddress) external; function isCToken(address tokenAddress) external view returns (bool); } // File: @sablier/protocol/contracts/interfaces/IERC1620.sol pragma solidity 0.5.11; /** * @title ERC-1620 Money Streaming Standard * @author Paul Razvan Berg - <[email protected]> * @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 balance, uint256 rate ); 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); } // File: @sablier/protocol/contracts/Types.sol pragma solidity 0.5.11; /** * @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; } struct CompoundingStreamVars { Exponential.Exp exchangeRateInitial; Exponential.Exp senderShare; Exponential.Exp recipientShare; bool isEntity; } } // File: @sablier/protocol/contracts/Sablier.sol pragma solidity 0.5.11; /** * @title Sablier's Money Streaming * @author Sablier */ contract Sablier is IERC1620, OwnableWithoutRenounce, PausableWithoutRenounce, Exponential, ReentrancyGuard { /*** Storage Properties ***/ /** * @notice In Exp terms, 1e18 is 1, or 100% */ uint256 constant hundredPercent = 1e18; /** * @notice In Exp terms, 1e16 is 0.01, or 1% */ uint256 constant onePercent = 1e16; /** * @notice Stores information about the initial state of the underlying of the cToken. */ mapping(uint256 => Types.CompoundingStreamVars) private compoundingStreamsVars; /** * @notice An instance of CTokenManager, responsible for whitelisting and discarding cTokens. */ ICTokenManager public cTokenManager; /** * @notice 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; /** * @notice The stream objects identifiable by their unsigned integer ids. */ mapping(uint256 => Types.Stream) private streams; /*** Events ***/ /** * @notice Emits when a compounding stream is successfully created. */ event CreateCompoundingStream( uint256 indexed streamId, uint256 exchangeRate, uint256 senderSharePercentage, uint256 recipientSharePercentage ); /** * @notice Emits when the owner discards a cToken. */ event PayInterest(uint256 streamId, uint256 senderInterest, uint256 recipientInterest, uint256 sablierInterest); /** * @notice Emits when the owner takes the earnings. */ event TakeEarnings(address indexed tokenAddress, uint256 indexed amount); /** * @notice Emits when the owner updates the percentage fee. */ event UpdateFee(uint256 indexed fee); /*** 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 id does not point to a valid stream. */ modifier streamExists(uint256 streamId) { require(streams[streamId].isEntity, "stream does not exist"); _; } /** * @dev Throws if the id does not point to a valid compounding stream. */ modifier compoundingStreamExists(uint256 streamId) { require(compoundingStreamsVars[streamId].isEntity, "compounding stream does not exist"); _; } /*** Contract Logic Starts Here */ constructor(address cTokenManagerAddress) public { OwnableWithoutRenounce.initialize(msg.sender); PausableWithoutRenounce.initialize(msg.sender); cTokenManager = ICTokenManager(cTokenManagerAddress); nextStreamId = 1; } /*** Owner Functions ***/ struct UpdateFeeLocalVars { MathError mathErr; uint256 feeMantissa; } /** * @notice Updates the Sablier fee. * @dev Throws if the caller is not the owner of the contract. * Throws if `feePercentage` is not lower or equal to 100. * @param feePercentage The new fee as a percentage. */ function updateFee(uint256 feePercentage) external onlyOwner { require(feePercentage <= 100, "fee percentage higher than 100%"); UpdateFeeLocalVars memory vars; /* `feePercentage` will be stored as a mantissa, so we scale it up by one percent in Exp terms. */ (vars.mathErr, vars.feeMantissa) = mulUInt(feePercentage, onePercent); /* * `mulUInt` can only return MathError.INTEGER_OVERFLOW but we control `onePercent` * and we know `feePercentage` is maximum 100. */ assert(vars.mathErr == MathError.NO_ERROR); fee = Exp({ mantissa: vars.feeMantissa }); emit UpdateFee(feePercentage); } struct TakeEarningsLocalVars { MathError mathErr; } /** * @notice Withdraws the earnings for the given token address. * @dev Throws if `amount` exceeds the available blance. * @param tokenAddress The address of the token to withdraw earnings for. * @param amount The amount of tokens to withdraw. */ function takeEarnings(address tokenAddress, uint256 amount) external onlyOwner nonReentrant { require(cTokenManager.isCToken(tokenAddress), "cToken is not whitelisted"); require(amount > 0, "amount is zero"); require(earnings[tokenAddress] >= amount, "amount exceeds the available balance"); TakeEarningsLocalVars memory vars; (vars.mathErr, earnings[tokenAddress]) = subUInt(earnings[tokenAddress], amount); /* * `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know `earnings[tokenAddress]` * is at least as big as `amount`. */ assert(vars.mathErr == MathError.NO_ERROR); emit TakeEarnings(tokenAddress, amount); require(IERC20(tokenAddress).transfer(msg.sender, amount), "token transfer failure"); } /*** View Functions ***/ /** * @notice 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. * @return The stream object. */ function getStream(uint256 streamId) external view 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; } /** * @notice Returns either the delta in seconds between `block.timestmap 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 whom to query the delta. * @return 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; } /** * @notice 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 whom to query the balance. * @param who The address for whom to query the balance. * @return The total funds allocated to `who` as uint256. */ function balanceOf(uint256 streamId, address who) public view 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; } /** * @notice Checks if the given id points to a compounding stream. * @param streamId The id of the compounding stream to check. * @return bool true=it is compounding stream, otherwise false. */ function isCompoundingStream(uint256 streamId) public view returns (bool) { return compoundingStreamsVars[streamId].isEntity; } /** * @notice Returns the compounding stream object with all its properties. * @dev Throws if the id does not point to a valid compounding stream. * @param streamId The id of the compounding stream to query. * @return The compounding stream object. */ function getCompoundingStream(uint256 streamId) external view streamExists(streamId) compoundingStreamExists(streamId) returns ( address sender, address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond, uint256 exchangeRateInitial, uint256 senderSharePercentage, uint256 recipientSharePercentage ) { 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; exchangeRateInitial = compoundingStreamsVars[streamId].exchangeRateInitial.mantissa; senderSharePercentage = compoundingStreamsVars[streamId].senderShare.mantissa; recipientSharePercentage = compoundingStreamsVars[streamId].recipientShare.mantissa; } struct InterestOfLocalVars { MathError mathErr; Exp exchangeRateDelta; Exp underlyingInterest; Exp netUnderlyingInterest; Exp senderUnderlyingInterest; Exp recipientUnderlyingInterest; Exp sablierUnderlyingInterest; Exp senderInterest; Exp recipientInterest; Exp sablierInterest; } /** * @notice Computes the interest accrued by keeping the amount of tokens in the contract. Returns (0, 0, 0) if * the stream is not a compounding stream. * @dev Throws if there is a math error. We do not assert the calculations which involve the current * exchange rate, because we can't know what value we'll get back from the cToken contract. * @return The interest accrued by the sender, the recipient and sablier, respectively, as uint256s. */ function interestOf(uint256 streamId, uint256 amount) public streamExists(streamId) returns (uint256 senderInterest, uint256 recipientInterest, uint256 sablierInterest) { if (!compoundingStreamsVars[streamId].isEntity) { return (0, 0, 0); } Types.Stream memory stream = streams[streamId]; Types.CompoundingStreamVars memory compoundingStreamVars = compoundingStreamsVars[streamId]; InterestOfLocalVars memory vars; /* * The exchange rate delta is a key variable, since it leads us to how much interest has been earned * since the compounding stream was created. */ Exp memory exchangeRateCurrent = Exp({ mantissa: ICERC20(stream.tokenAddress).exchangeRateCurrent() }); if (exchangeRateCurrent.mantissa <= compoundingStreamVars.exchangeRateInitial.mantissa) { return (0, 0, 0); } (vars.mathErr, vars.exchangeRateDelta) = subExp(exchangeRateCurrent, compoundingStreamVars.exchangeRateInitial); assert(vars.mathErr == MathError.NO_ERROR); /* Calculate how much interest has been earned by holding `amount` in the smart contract. */ (vars.mathErr, vars.underlyingInterest) = mulScalar(vars.exchangeRateDelta, amount); require(vars.mathErr == MathError.NO_ERROR, "interest calculation error"); /* Calculate our share from that interest. */ if (fee.mantissa == hundredPercent) { (vars.mathErr, vars.sablierInterest) = divExp(vars.underlyingInterest, exchangeRateCurrent); require(vars.mathErr == MathError.NO_ERROR, "sablier interest conversion error"); return (0, 0, truncate(vars.sablierInterest)); } else if (fee.mantissa == 0) { vars.sablierUnderlyingInterest = Exp({ mantissa: 0 }); vars.netUnderlyingInterest = vars.underlyingInterest; } else { (vars.mathErr, vars.sablierUnderlyingInterest) = mulExp(vars.underlyingInterest, fee); require(vars.mathErr == MathError.NO_ERROR, "sablier interest calculation error"); /* Calculate how much interest is left for the sender and the recipient. */ (vars.mathErr, vars.netUnderlyingInterest) = subExp( vars.underlyingInterest, vars.sablierUnderlyingInterest ); /* * `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `sablierUnderlyingInterest` * is less or equal than `underlyingInterest`, because we control the value of `fee`. */ assert(vars.mathErr == MathError.NO_ERROR); } /* Calculate the sender's share of the interest. */ (vars.mathErr, vars.senderUnderlyingInterest) = mulExp( vars.netUnderlyingInterest, compoundingStreamVars.senderShare ); require(vars.mathErr == MathError.NO_ERROR, "sender interest calculation error"); /* Calculate the recipient's share of the interest. */ (vars.mathErr, vars.recipientUnderlyingInterest) = subExp( vars.netUnderlyingInterest, vars.senderUnderlyingInterest ); /* * `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `senderUnderlyingInterest` * is less or equal than `netUnderlyingInterest`, because `senderShare` is bounded between 1e16 and 1e18. */ assert(vars.mathErr == MathError.NO_ERROR); /* Convert the interest to the equivalent cToken denomination. */ (vars.mathErr, vars.senderInterest) = divExp(vars.senderUnderlyingInterest, exchangeRateCurrent); require(vars.mathErr == MathError.NO_ERROR, "sender interest conversion error"); (vars.mathErr, vars.recipientInterest) = divExp(vars.recipientUnderlyingInterest, exchangeRateCurrent); require(vars.mathErr == MathError.NO_ERROR, "recipient interest conversion error"); (vars.mathErr, vars.sablierInterest) = divExp(vars.sablierUnderlyingInterest, exchangeRateCurrent); require(vars.mathErr == MathError.NO_ERROR, "sablier interest conversion error"); /* Truncating the results means losing everything on the last 1e18 positions of the mantissa */ return (truncate(vars.senderInterest), truncate(vars.recipientInterest), truncate(vars.sablierInterest)); } /** * @notice Returns the amount of interest that has been accrued for the given token address. * @param tokenAddress The address of the token to get the earnings for. * @return The amount of interest as uint256. */ function getEarnings(address tokenAddress) external view returns (uint256) { require(cTokenManager.isCToken(tokenAddress), "token is not cToken"); return earnings[tokenAddress]; } /*** 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 whenNotPaused 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"); /* This condition avoids dealing with remainders */ 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 CreateCompoundingStreamLocalVars { MathError mathErr; uint256 shareSum; uint256 underlyingBalance; uint256 senderShareMantissa; uint256 recipientShareMantissa; } /** * @notice Creates a new compounding stream funded by `msg.sender` and paid towards `recipient`. * @dev Inherits all security checks from `createStream`. * Throws if the cToken is not whitelisted. * Throws if the sender share percentage and the recipient share percentage do not sum up to 100. * Throws if the the sender share mantissa calculation has a math error. * Throws if the the recipient share mantissa calculation has a math error. * @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. * @param senderSharePercentage The sender's share of the interest, as a percentage. * @param recipientSharePercentage The sender's share of the interest, as a percentage. * @return The uint256 id of the newly created compounding stream. */ function createCompoundingStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 senderSharePercentage, uint256 recipientSharePercentage ) external whenNotPaused returns (uint256) { require(cTokenManager.isCToken(tokenAddress), "cToken is not whitelisted"); CreateCompoundingStreamLocalVars memory vars; /* Ensure that the interest shares sum up to 100%. */ (vars.mathErr, vars.shareSum) = addUInt(senderSharePercentage, recipientSharePercentage); require(vars.mathErr == MathError.NO_ERROR, "share sum calculation error"); require(vars.shareSum == 100, "shares do not sum up to 100"); uint256 streamId = createStream(recipient, deposit, tokenAddress, startTime, stopTime); /* * `senderSharePercentage` and `recipientSharePercentage` will be stored as mantissas, so we scale them up * by one percent in Exp terms. */ (vars.mathErr, vars.senderShareMantissa) = mulUInt(senderSharePercentage, onePercent); /* * `mulUInt` can only return MathError.INTEGER_OVERFLOW but we control `onePercent` and * we know `senderSharePercentage` is maximum 100. */ assert(vars.mathErr == MathError.NO_ERROR); (vars.mathErr, vars.recipientShareMantissa) = mulUInt(recipientSharePercentage, onePercent); /* * `mulUInt` can only return MathError.INTEGER_OVERFLOW but we control `onePercent` and * we know `recipientSharePercentage` is maximum 100. */ assert(vars.mathErr == MathError.NO_ERROR); /* Create and store the compounding stream vars. */ uint256 exchangeRateCurrent = ICERC20(tokenAddress).exchangeRateCurrent(); compoundingStreamsVars[streamId] = Types.CompoundingStreamVars({ exchangeRateInitial: Exp({ mantissa: exchangeRateCurrent }), isEntity: true, recipientShare: Exp({ mantissa: vars.recipientShareMantissa }), senderShare: Exp({ mantissa: vars.senderShareMantissa }) }); emit CreateCompoundingStream(streamId, exchangeRateCurrent, senderSharePercentage, recipientSharePercentage); return streamId; } /** * @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 whenNotPaused nonReentrant streamExists(streamId) onlySenderOrRecipient(streamId) returns (bool) { require(amount > 0, "amount is zero"); Types.Stream memory stream = streams[streamId]; uint256 balance = balanceOf(streamId, stream.recipient); require(balance >= amount, "amount exceeds the available balance"); if (!compoundingStreamsVars[streamId].isEntity) { withdrawFromStreamInternal(streamId, amount); } else { withdrawFromCompoundingStreamInternal(streamId, 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 nonReentrant streamExists(streamId) onlySenderOrRecipient(streamId) returns (bool) { if (!compoundingStreamsVars[streamId].isEntity) { cancelStreamInternal(streamId); } else { cancelCompoundingStreamInternal(streamId); } return true; } /*** Internal Effects & Interactions Functions ***/ struct WithdrawFromStreamInternalLocalVars { MathError mathErr; } /** * @notice Makes the withdrawal to the recipient of the stream. * @dev If the stream balance has been depleted to 0, the stream object is deleted * to save gas and optimise contract storage. * Throws if the stream balance calculation has a math error. * Throws if there is a token transfer failure. */ function withdrawFromStreamInternal(uint256 streamId, uint256 amount) internal { Types.Stream memory stream = streams[streamId]; WithdrawFromStreamInternalLocalVars memory vars; (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`. See the `require` check in `withdrawFromInternal`. */ 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); } struct WithdrawFromCompoundingStreamInternalLocalVars { MathError mathErr; uint256 amountWithoutSenderInterest; uint256 netWithdrawalAmount; } /** * @notice Withdraws to the recipient's account and pays the accrued interest to all parties. * @dev If the stream balance has been depleted to 0, the stream object to save gas and optimise * contract storage. * Throws if there is a math error. * Throws if there is a token transfer failure. */ function withdrawFromCompoundingStreamInternal(uint256 streamId, uint256 amount) internal { Types.Stream memory stream = streams[streamId]; WithdrawFromCompoundingStreamInternalLocalVars memory vars; /* Calculate the interest earned by each party for keeping `stream.balance` in the smart contract. */ (uint256 senderInterest, uint256 recipientInterest, uint256 sablierInterest) = interestOf(streamId, amount); /* * Calculate the net withdrawal amount by subtracting `senderInterest` and `sablierInterest`. * Because the decimal points are lost when we truncate Exponentials, the recipient will implicitly earn * `recipientInterest` plus a tiny-weeny amount of interest, max 2e-8 in cToken denomination. */ (vars.mathErr, vars.amountWithoutSenderInterest) = subUInt(amount, senderInterest); require(vars.mathErr == MathError.NO_ERROR, "amount without sender interest calculation error"); (vars.mathErr, vars.netWithdrawalAmount) = subUInt(vars.amountWithoutSenderInterest, sablierInterest); require(vars.mathErr == MathError.NO_ERROR, "net withdrawal amount calculation error"); /* Subtract `amount` from the remaining balance of the stream. */ (vars.mathErr, streams[streamId].remainingBalance) = subUInt(stream.remainingBalance, amount); require(vars.mathErr == MathError.NO_ERROR, "balance subtraction calculation error"); /* Delete the objects from storage if the remainig balance has been depleted to 0. */ if (streams[streamId].remainingBalance == 0) { delete streams[streamId]; delete compoundingStreamsVars[streamId]; } /* Add the sablier interest to the earnings for this cToken. */ (vars.mathErr, earnings[stream.tokenAddress]) = addUInt(earnings[stream.tokenAddress], sablierInterest); require(vars.mathErr == MathError.NO_ERROR, "earnings addition calculation error"); /* Transfer the tokens to the sender and the recipient. */ ICERC20 cToken = ICERC20(stream.tokenAddress); if (senderInterest > 0) require(cToken.transfer(stream.sender, senderInterest), "sender token transfer failure"); require(cToken.transfer(stream.recipient, vars.netWithdrawalAmount), "recipient token transfer failure"); emit WithdrawFromStream(streamId, stream.recipient, vars.netWithdrawalAmount); emit PayInterest(streamId, senderInterest, recipientInterest, sablierInterest); } /** * @notice Cancels the stream and transfers the tokens back on a pro rata basis. * @dev The stream and compounding stream vars objects get deleted to save gas * and optimise contract storage. * Throws if there is a token transfer failure. */ function cancelStreamInternal(uint256 streamId) internal { 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); } struct CancelCompoundingStreamInternal { MathError mathErr; uint256 netSenderBalance; uint256 recipientBalanceWithoutSenderInterest; uint256 netRecipientBalance; } /** * @notice Cancels the stream, transfers the tokens back on a pro rata basis and pays the accrued * interest to all parties. * @dev Importantly, the money that has not been streamed yet is not considered chargeable. * All the interest generated by that underlying will be returned to the sender. * Throws if there is a math error. * Throws if there is a token transfer failure. */ function cancelCompoundingStreamInternal(uint256 streamId) internal { Types.Stream memory stream = streams[streamId]; CancelCompoundingStreamInternal memory vars; /* * The sender gets back all the money that has not been streamed so far. By that, we mean both * the underlying amount and the interest generated by it. */ uint256 senderBalance = balanceOf(streamId, stream.sender); uint256 recipientBalance = balanceOf(streamId, stream.recipient); /* Calculate the interest earned by each party for keeping `recipientBalance` in the smart contract. */ (uint256 senderInterest, uint256 recipientInterest, uint256 sablierInterest) = interestOf( streamId, recipientBalance ); /* * We add `senderInterest` to `senderBalance` to compute the net balance for the sender. * After this, the rest of the function is similar to `withdrawFromCompoundingStreamInternal`, except * we add the sender's share of the interest generated by `recipientBalance` to `senderBalance`. */ (vars.mathErr, vars.netSenderBalance) = addUInt(senderBalance, senderInterest); require(vars.mathErr == MathError.NO_ERROR, "net sender balance calculation error"); /* * Calculate the net withdrawal amount by subtracting `senderInterest` and `sablierInterest`. * Because the decimal points are lost when we truncate Exponentials, the recipient will implicitly earn * `recipientInterest` plus a tiny-weeny amount of interest, max 2e-8 in cToken denomination. */ (vars.mathErr, vars.recipientBalanceWithoutSenderInterest) = subUInt(recipientBalance, senderInterest); require(vars.mathErr == MathError.NO_ERROR, "recipient balance without sender interest calculation error"); (vars.mathErr, vars.netRecipientBalance) = subUInt(vars.recipientBalanceWithoutSenderInterest, sablierInterest); require(vars.mathErr == MathError.NO_ERROR, "net recipient balance calculation error"); /* Add the sablier interest to the earnings attributed to this cToken. */ (vars.mathErr, earnings[stream.tokenAddress]) = addUInt(earnings[stream.tokenAddress], sablierInterest); require(vars.mathErr == MathError.NO_ERROR, "earnings addition calculation error"); /* Delete the objects from storage. */ delete streams[streamId]; delete compoundingStreamsVars[streamId]; /* Transfer the tokens to the sender and the recipient. */ IERC20 token = IERC20(stream.tokenAddress); if (vars.netSenderBalance > 0) require(token.transfer(stream.sender, vars.netSenderBalance), "sender token transfer failure"); if (vars.netRecipientBalance > 0) require(token.transfer(stream.recipient, vars.netRecipientBalance), "recipient token transfer failure"); emit CancelStream(streamId, stream.sender, stream.recipient, vars.netSenderBalance, vars.netRecipientBalance); emit PayInterest(streamId, senderInterest, recipientInterest, sablierInterest); } } // File: contracts/Payroll.sol pragma solidity 0.5.11; /** * @title Payroll Proxy * @author Sablier */ contract Payroll is Initializable, OwnableWithoutRenounce, Exponential, GSNRecipient, GSNBouncerSignature { /*** Storage Properties ***/ /** * @notice Container for salary information * @member company The address of the company which funded this salary * @member isEntity bool true=object exists, otherwise false * @member streamId The id of the stream in the Sablier contract */ struct Salary { address company; bool isEntity; uint256 streamId; } /** * @notice Counter for new salary ids. */ uint256 public nextSalaryId; /** * @notice Whitelist of accounts able to call the withdrawal function for a given stream so * employees don't have to pay gas. */ mapping(address => mapping(uint256 => bool)) public relayers; /** * @notice An instance of Sablier, the contract responsible for creating, withdrawing from and cancelling streams. */ Sablier public sablier; /** * @notice The salary objects identifiable by their unsigned integer ids. */ mapping(uint256 => Salary) private salaries; /*** Events ***/ /** * @notice Emits when a salary is successfully created. */ event CreateSalary(uint256 indexed salaryId, uint256 indexed streamId); /** * @notice Emits when a compounding salary is successfully created. */ event CreateCompoundingSalary(uint256 indexed salaryId, uint256 indexed streamId); /** * @notice Emits when the employee withdraws a portion or all their pro rata share of the stream. */ event WithdrawFromSalary(uint256 indexed salaryId, uint256 indexed streamId); /** * @notice Emits when a salary is successfully cancelled and both parties get their pro rata * share of the available funds. */ event CancelSalary(uint256 indexed salaryId, uint256 indexed streamId); /** * @dev Throws if the caller is not the company or the employee. */ modifier onlyCompanyOrEmployee(uint256 salaryId) { Salary memory salary = salaries[salaryId]; (, address employee, , , , , , ) = sablier.getStream(salary.streamId); require( _msgSender() == salary.company || _msgSender() == employee, "caller is not the company or the employee" ); _; } /** * @dev Throws if the caller is not the employee or an approved relayer. */ modifier onlyEmployeeOrRelayer(uint256 salaryId) { Salary memory salary = salaries[salaryId]; (, address employee, , , , , , ) = sablier.getStream(salary.streamId); require( _msgSender() == employee || relayers[_msgSender()][salaryId], "caller is not the employee or a relayer" ); _; } /** * @dev Throws if the id does not point to a valid salary. */ modifier salaryExists(uint256 salaryId) { require(salaries[salaryId].isEntity, "salary does not exist"); _; } /*** Contract Logic Starts Here ***/ /** * @notice Only called once after the contract is deployed. We ask for the owner and the signer address * to be specified as parameters to avoid handling `msg.sender` directly. * @dev The `initializer` modifier ensures that the function can only be called once. * @param ownerAddress The address of the contract owner. * @param signerAddress The address of the account able to authorise relayed transactions. * @param sablierAddress The address of the Sablier contract. */ function initialize(address ownerAddress, address signerAddress, address sablierAddress) public initializer { OwnableWithoutRenounce.initialize(ownerAddress); GSNRecipient.initialize(); GSNBouncerSignature.initialize(signerAddress); sablier = Sablier(sablierAddress); nextSalaryId = 1; } /*** Admin ***/ /** * @notice Whitelists a relayer to process withdrawals so the employee doesn't have to pay gas. * @dev Throws if the caller is not the owner of the contract. * Throws if the id does not point to a valid salary. * Throws if the relayer is whitelisted. * @param relayer The address of the relayer account. * @param salaryId The id of the salary to whitelist the relayer for. */ function whitelistRelayer(address relayer, uint256 salaryId) external onlyOwner salaryExists(salaryId) { require(!relayers[relayer][salaryId], "relayer is whitelisted"); relayers[relayer][salaryId] = true; } /** * @notice Discard a previously whitelisted relayer to prevent them from processing withdrawals. * @dev Throws if the caller is not the owner of the contract. * Throws if the relayer is not whitelisted. * @param relayer The address of the relayer account. * @param salaryId The id of the salary to discard the relayer for. */ function discardRelayer(address relayer, uint256 salaryId) external onlyOwner { require(relayers[relayer][salaryId], "relayer is not whitelisted"); relayers[relayer][salaryId] = false; } /*** View Functions ***/ /** * @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the * recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not). * * The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call * calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas, * and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the * recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for * replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold * a signature over all or some of the previous values. * * Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code, * values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions. * * {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered * rejected. A regular revert will also trigger a rejection. */ function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 ) external view returns (uint256, bytes memory) { /** * `nonce` prevents replays on RelayHub * `getHubAddr` prevents replays in multiple RelayHubs * `address(this)` prevents replays in multiple recipients */ bytes memory blob = abi.encodePacked( relay, from, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, getHubAddr(), address(this) ); if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) == owner()) { return _approveRelayedCall(); } else { return _rejectRelayedCall(uint256(GSNBouncerSignatureErrorCodes.INVALID_SIGNER)); } } /** * @notice Returns the salary object with all its properties. * @dev Throws if the id does not point to a valid salary. * @param salaryId The id of the salary to query. * @return The salary object. */ function getSalary(uint256 salaryId) public view salaryExists(salaryId) returns ( address company, address employee, uint256 salary, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 rate ) { company = salaries[salaryId].company; (, employee, salary, tokenAddress, startTime, stopTime, remainingBalance, rate) = sablier.getStream( salaries[salaryId].streamId ); } /*** Public Effects & Interactions Functions ***/ struct CreateSalaryLocalVars { MathError mathErr; } /** * @notice Creates a new salary funded by `msg.sender` and paid towards `employee`. * @dev Throws if there is a math error. * Throws if there is a token transfer failure. * @param employee The address of the employee who receives the salary. * @param salary The amount of tokens 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 salary. */ function createSalary(address employee, uint256 salary, address tokenAddress, uint256 startTime, uint256 stopTime) external returns (uint256 salaryId) { /* Transfer the tokens to this contract. */ require(IERC20(tokenAddress).transferFrom(_msgSender(), address(this), salary), "token transfer failure"); /* Approve the Sablier contract to spend from our tokens. */ require(IERC20(tokenAddress).approve(address(sablier), salary), "token approval failure"); /* Create the stream. */ uint256 streamId = sablier.createStream(employee, salary, tokenAddress, startTime, stopTime); salaryId = nextSalaryId; salaries[nextSalaryId] = Salary({ company: _msgSender(), isEntity: true, streamId: streamId }); /* Increment the next salary id. */ CreateSalaryLocalVars memory vars; (vars.mathErr, nextSalaryId) = addUInt(nextSalaryId, uint256(1)); require(vars.mathErr == MathError.NO_ERROR, "next stream id calculation error"); emit CreateSalary(salaryId, streamId); } /** * @notice Creates a new compounding salary funded by `msg.sender` and paid towards `employee`. * @dev There's a bit of redundancy between `createSalary` and this function, but one has to * call `sablier.createStream` and the other `sablier.createCompoundingStream`, so it's not * worth it to run DRY code. * Throws if there is a math error. * Throws if there is a token transfer failure. * @param employee The address of the employee who receives the salary. * @param salary The amount of tokens 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. * @param senderSharePercentage The sender's share of the interest, as a percentage. * @param recipientSharePercentage The sender's share of the interest, as a percentage. * @return The uint256 id of the newly created compounding salary. */ function createCompoundingSalary( address employee, uint256 salary, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 senderSharePercentage, uint256 recipientSharePercentage ) external returns (uint256 salaryId) { /* Transfer the tokens to this contract. */ require(IERC20(tokenAddress).transferFrom(_msgSender(), address(this), salary), "token transfer failure"); /* Approve the Sablier contract to spend from our tokens. */ require(IERC20(tokenAddress).approve(address(sablier), salary), "token approval failure"); /* Create the stream. */ uint256 streamId = sablier.createCompoundingStream( employee, salary, tokenAddress, startTime, stopTime, senderSharePercentage, recipientSharePercentage ); salaryId = nextSalaryId; salaries[nextSalaryId] = Salary({ company: _msgSender(), isEntity: true, streamId: streamId }); /* Increment the next salary id. */ CreateSalaryLocalVars memory vars; (vars.mathErr, nextSalaryId) = addUInt(nextSalaryId, uint256(1)); require(vars.mathErr == MathError.NO_ERROR, "next stream id calculation error"); /* We don't emit a different event for compounding salaries because we emit CreateCompoundingStream. */ emit CreateSalary(salaryId, streamId); } struct CancelSalaryLocalVars { MathError mathErr; uint256 netCompanyBalance; } /** * @notice Withdraws from the contract to the employee's account. * @dev Throws if the id does not point to a valid salary. * Throws if the caller is not the employee or a relayer. * Throws if there is a token transfer failure. * @param salaryId The id of the salary to withdraw from. * @param amount The amount of tokens to withdraw. * @return bool true=success, false otherwise. */ function withdrawFromSalary(uint256 salaryId, uint256 amount) external salaryExists(salaryId) onlyEmployeeOrRelayer(salaryId) returns (bool success) { Salary memory salary = salaries[salaryId]; success = sablier.withdrawFromStream(salary.streamId, amount); emit WithdrawFromSalary(salaryId, salary.streamId); } /** * @notice Cancels the salary and transfers the tokens back on a pro rata basis. * @dev Throws if the id does not point to a valid salary. * Throws if the caller is not the company or the employee. * Throws if there is a token transfer failure. * @param salaryId The id of the salary to cancel. * @return bool true=success, false otherwise. */ function cancelSalary(uint256 salaryId) external salaryExists(salaryId) onlyCompanyOrEmployee(salaryId) returns (bool success) { Salary memory salary = salaries[salaryId]; /* We avoid storing extraneous data twice, so we read the token address from Sablier. */ (, address employee, , address tokenAddress, , , , ) = sablier.getStream(salary.streamId); uint256 companyBalance = sablier.balanceOf(salary.streamId, address(this)); /** * The company gets all the money that has not been streamed yet, plus all the interest earned by what's left. * Not all streams are compounding and `companyBalance` coincides with `netCompanyBalance` then. */ CancelSalaryLocalVars memory vars; if (!sablier.isCompoundingStream(salary.streamId)) { vars.netCompanyBalance = companyBalance; } else { uint256 employeeBalance = sablier.balanceOf(salary.streamId, employee); (uint256 companyInterest, , ) = sablier.interestOf(salary.streamId, employeeBalance); (vars.mathErr, vars.netCompanyBalance) = addUInt(companyBalance, companyInterest); require(vars.mathErr == MathError.NO_ERROR, "net company balance calculation error"); } /* Delete the salary object to save gas. */ delete salaries[salaryId]; success = sablier.cancelStream(salary.streamId); /* Transfer the tokens to the company. */ if (vars.netCompanyBalance > 0) require( IERC20(tokenAddress).transfer(salary.company, vars.netCompanyBalance), "company token transfer failure" ); emit CancelSalary(salaryId, salary.streamId); } }
solhint-disable-next-line no-inline-assembly
function _getRelayHub() internal view returns (address relayHub) { bytes32 slot = RELAY_HUB_ADDRESS_STORAGE_SLOT; assembly { relayHub := sload(slot) } }
5,427,103
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 27186, 8182, 1435, 2713, 1476, 1135, 261, 2867, 18874, 8182, 13, 288, 203, 3639, 1731, 1578, 4694, 273, 15375, 5255, 67, 44, 3457, 67, 15140, 67, 19009, 67, 55, 1502, 56, 31, 203, 3639, 19931, 288, 203, 5411, 18874, 8182, 519, 272, 945, 12, 14194, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x00416B9d728069eDB0cEb04bC2b203fA7336d1F1 //Contract name: AversafeSeedCrowdsale //Balance: 0 Ether //Verification Date: 11/29/2017 //Transacion Count: 36 // CODE STARTS HERE /* Copyright 2017 Cofound.it. 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.13; contract ReentrancyHandlingContract { bool locked; modifier noReentrancy() { require(!locked); locked = true; _; locked = false; } } contract Owned { address public owner; address public newOwner; function Owned() public { owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } event OwnerUpdate(address _prevOwner, address _newOwner); } contract PriorityPassInterface { function getAccountLimit(address _accountAddress) public constant returns (uint); function getAccountActivity(address _accountAddress) public constant returns (bool); } contract ERC20TokenInterface { function totalSupply() public constant returns (uint256 _totalSupply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract SeedCrowdsaleContract is ReentrancyHandlingContract, Owned { struct ContributorData { uint contributionAmount; } mapping(address => ContributorData) public contributorList; uint public nextContributorIndex; mapping(uint => address) public contributorIndexes; state public crowdsaleState = state.pendingStart; enum state { pendingStart, priorityPass, openedPriorityPass, crowdsaleEnded } uint public presaleStartTime; uint public presaleUnlimitedStartTime; uint public crowdsaleEndedTime; event PresaleStarted(uint blocktime); event PresaleUnlimitedStarted(uint blocktime); event CrowdsaleEnded(uint blocktime); event ErrorSendingETH(address to, uint amount); event MinCapReached(uint blocktime); event MaxCapReached(uint blocktime); event ContributionMade(address indexed contributor, uint amount); PriorityPassInterface priorityPassContract = PriorityPassInterface(0x0); uint public minCap; uint public maxP1Cap; uint public maxCap; uint public ethRaised; address public multisigAddress; uint nextContributorToClaim; mapping(address => bool) hasClaimedEthWhenFail; // // Unnamed function that runs when eth is sent to the contract // @payable // function() noReentrancy payable public { require(msg.value != 0); // Throw if value is 0 require(crowdsaleState != state.crowdsaleEnded); // Check if crowdsale has ended bool stateChanged = checkCrowdsaleState(); // Check blocks time and calibrate crowdsale state if (crowdsaleState == state.priorityPass) { if (priorityPassContract.getAccountActivity(msg.sender)) { // Check if contributor is in priorityPass processTransaction(msg.sender, msg.value); // Process transaction and issue tokens } else { refundTransaction(stateChanged); // Set state and return funds or throw } } else if (crowdsaleState == state.openedPriorityPass) { if (priorityPassContract.getAccountActivity(msg.sender)) { // Check if contributor is in priorityPass processTransaction(msg.sender, msg.value); // Process transaction and issue tokens } else { refundTransaction(stateChanged); // Set state and return funds or throw } } else { refundTransaction(stateChanged); // Set state and return funds or throw } } // // @internal checks crowdsale state and emits events it // @returns boolean // function checkCrowdsaleState() internal returns (bool) { if (ethRaised == maxCap && crowdsaleState != state.crowdsaleEnded) { // Check if max cap is reached crowdsaleState = state.crowdsaleEnded; MaxCapReached(block.timestamp); // Close the crowdsale CrowdsaleEnded(block.timestamp); // Raise event return true; } if (block.timestamp > presaleStartTime && block.timestamp <= presaleUnlimitedStartTime) { // Check if we are in presale phase if (crowdsaleState != state.priorityPass) { // Check if state needs to be changed crowdsaleState = state.priorityPass; // Set new state PresaleStarted(block.timestamp); // Raise event return true; } } else if (block.timestamp > presaleUnlimitedStartTime && block.timestamp <= crowdsaleEndedTime) { // Check if we are in presale unlimited phase if (crowdsaleState != state.openedPriorityPass) { // Check if state needs to be changed crowdsaleState = state.openedPriorityPass; // Set new state PresaleUnlimitedStarted(block.timestamp); // Raise event return true; } } else { if (crowdsaleState != state.crowdsaleEnded && block.timestamp > crowdsaleEndedTime) {// Check if crowdsale is over crowdsaleState = state.crowdsaleEnded; // Set new state CrowdsaleEnded(block.timestamp); // Raise event return true; } } return false; } // // @internal determines if return eth or throw according to changing state // @param _stateChanged boolean message about state change // function refundTransaction(bool _stateChanged) internal { if (_stateChanged) { msg.sender.transfer(msg.value); } else { revert(); } } // // Getter to calculate how much user can contribute // @param _contributor address of the contributor // function calculateMaxContribution(address _contributor) constant public returns (uint maxContribution) { uint maxContrib; if (crowdsaleState == state.priorityPass) { // Check if we are in priority pass maxContrib = priorityPassContract.getAccountLimit(_contributor) - contributorList[_contributor].contributionAmount; if (maxContrib > (maxP1Cap - ethRaised)) { // Check if max contribution is more that max cap maxContrib = maxP1Cap - ethRaised; // Alter max cap } } else { maxContrib = maxCap - ethRaised; // Alter max cap } return maxContrib; } // // Return if there is overflow of contributed eth // @internal processes transactions // @param _contributor address of an contributor // @param _amount contributed amount // function processTransaction(address _contributor, uint _amount) internal { uint maxContribution = calculateMaxContribution(_contributor); // Calculate max users contribution uint contributionAmount = _amount; uint returnAmount = 0; if (maxContribution < _amount) { // Check if max contribution is lower than _amount sent contributionAmount = maxContribution; // Set that user contributes his maximum alowed contribution returnAmount = _amount - maxContribution; // Calculate how much he must get back } if (ethRaised + contributionAmount >= minCap && minCap > ethRaised) { MinCapReached(block.timestamp); } if (contributorList[_contributor].contributionAmount == 0) { // Check if contributor has already contributed contributorList[_contributor].contributionAmount = contributionAmount; // Set their contribution contributorIndexes[nextContributorIndex] = _contributor; // Set contributors index nextContributorIndex++; } else { contributorList[_contributor].contributionAmount += contributionAmount; // Add contribution amount to existing contributor } ethRaised += contributionAmount; // Add to eth raised ContributionMade(msg.sender, contributionAmount); // Raise event about contribution if (returnAmount != 0) { _contributor.transfer(returnAmount); // Return overflow of ether } } // // Recovers ERC20 tokens other than eth that are send to this address // @owner refunds the erc20 tokens // @param _tokenAddress address of the erc20 token // @param _to address to where tokens should be send to // @param _amount amount of tokens to refund // function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public { ERC20TokenInterface(_tokenAddress).transfer(_to, _amount); } // // withdrawEth when minimum cap is reached // @owner sets contributions to withdraw // function withdrawEth() onlyOwner public { require(this.balance != 0); require(ethRaised >= minCap); pendingEthWithdrawal = this.balance; } uint public pendingEthWithdrawal; // // pulls the funds that were set to send with calling of // withdrawEth when minimum cap is reached // @multisig pulls the contributions to self // function pullBalance() public { require(msg.sender == multisigAddress); require(pendingEthWithdrawal > 0); multisigAddress.transfer(pendingEthWithdrawal); pendingEthWithdrawal = 0; } // // Owner can batch return contributors contributions(eth) // @owner returns contributions // @param _numberOfReturns number of returns to do in one transaction // function batchReturnEthIfFailed(uint _numberOfReturns) onlyOwner public { require(block.timestamp > crowdsaleEndedTime && ethRaised < minCap); // Check if crowdsale has failed address currentParticipantAddress; uint contribution; for (uint cnt = 0; cnt < _numberOfReturns; cnt++) { currentParticipantAddress = contributorIndexes[nextContributorToClaim]; // Get next unclaimed participant if (currentParticipantAddress == 0x0) { return; // Check if all the participants were compensated } if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if participant has already claimed contribution = contributorList[currentParticipantAddress].contributionAmount; // Get contribution of participant hasClaimedEthWhenFail[currentParticipantAddress] = true; // Set that he has claimed if (!currentParticipantAddress.send(contribution)) { // Refund eth ErrorSendingETH(currentParticipantAddress, contribution); // If there is an issue raise event for manual recovery } } nextContributorToClaim += 1; // Repeat } } // // If there were any issue with refund owner can withdraw eth at the end for manual recovery // @owner withdraws remaining funds // function withdrawRemainingBalanceForManualRecovery() onlyOwner public { require(this.balance != 0); // Check if there are any eth to claim require(block.timestamp > crowdsaleEndedTime); // Check if crowdsale is over require(contributorIndexes[nextContributorToClaim] == 0x0); // Check if all the users were refunded multisigAddress.transfer(this.balance); // Withdraw to multisig for manual processing } // // Owner can set multisig address for crowdsale // @owner sets an address where funds will go // @param _newAddress // function setMultisigAddress(address _newAddress) onlyOwner public { multisigAddress = _newAddress; } // // Setter for the whitelist contract // @owner sets address of whitelist contract // @param address // function setPriorityPassContract(address _newAddress) onlyOwner public { priorityPassContract = PriorityPassInterface(_newAddress); } // // Getter for the whitelist contract // @returns white list contract address // function priorityPassContractAddress() constant public returns (address) { return address(priorityPassContract); } // // Before crowdsale starts owner can calibrate time of crowdsale stages // @owner sends new times for the sale // @param _presaleStartTime timestamp for sale limited start // @param _presaleUnlimitedStartTime timestamp for sale unlimited // @param _crowdsaleEndedTime timestamp for ending sale // function setCrowdsaleTimes(uint _presaleStartTime, uint _presaleUnlimitedStartTime, uint _crowdsaleEndedTime) onlyOwner public { require(crowdsaleState == state.pendingStart); // Check if crowdsale has started require(_presaleStartTime != 0); // Check if any value is 0 require(_presaleStartTime < _presaleUnlimitedStartTime); // Check if presaleUnlimitedStartTime is set properly require(_presaleUnlimitedStartTime != 0); // Check if any value is 0 require(_presaleUnlimitedStartTime < _crowdsaleEndedTime); // Check if crowdsaleEndedTime is set properly require(_crowdsaleEndedTime != 0); // Check if any value is 0 presaleStartTime = _presaleStartTime; presaleUnlimitedStartTime = _presaleUnlimitedStartTime; crowdsaleEndedTime = _crowdsaleEndedTime; } } contract AversafeSeedCrowdsale is SeedCrowdsaleContract { function AversafeSeedCrowdsale() { presaleStartTime = 1512032400; presaleUnlimitedStartTime = 1512063000; crowdsaleEndedTime = 1512140400; minCap = 451 ether; maxP1Cap = 802 ether; maxCap = 891 ether; } }
Getter to calculate how much user can contribute @param _contributor address of the contributor
function calculateMaxContribution(address _contributor) constant public returns (uint maxContribution) { uint maxContrib; maxContrib = priorityPassContract.getAccountLimit(_contributor) - contributorList[_contributor].contributionAmount; }
1,003,025
[ 1, 8461, 358, 4604, 3661, 9816, 729, 848, 356, 887, 225, 389, 591, 19293, 1758, 434, 326, 31123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4604, 2747, 442, 4027, 12, 2867, 389, 591, 19293, 13, 5381, 1071, 1135, 261, 11890, 943, 442, 4027, 13, 288, 203, 565, 2254, 943, 442, 665, 31, 203, 203, 1377, 943, 442, 665, 273, 4394, 6433, 8924, 18, 588, 3032, 3039, 24899, 591, 19293, 13, 300, 31123, 682, 63, 67, 591, 19293, 8009, 591, 4027, 6275, 31, 203, 203, 1377, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2b09AA973763e0d7dBa97D89A2a820a0Fc4ee0A5/sources/lib/solady/src/utils/SSTORE2.sol
@notice Read and write to persistent storage at a fraction of the cost. @author Solady (https://github.com/vectorized/solmady/blob/main/src/utils/SSTORE2.sol) @author Saw-mon-and-Natalie (https://github.com/Saw-mon-and-Natalie) @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol) @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
library SSTORE2 { uint256 internal constant DATA_OFFSET = 1; error DeploymentFailed(); error InvalidPointer(); error ReadOutOfBounds(); pragma solidity ^0.8.4; function write(bytes memory data) internal returns (address pointer) { assembly { let originalDataLength := mload(data) let dataSize := add(originalDataLength, DATA_OFFSET) mstore( data, or( 0x61000080600a3d393df300, shl(0x40, dataSize) ) ) pointer := create(0, add(data, 0x15), add(dataSize, 0xa)) if iszero(pointer) { mstore(0x00, 0x30116425) revert(0x1c, 0x04) } } } function write(bytes memory data) internal returns (address pointer) { assembly { let originalDataLength := mload(data) let dataSize := add(originalDataLength, DATA_OFFSET) mstore( data, or( 0x61000080600a3d393df300, shl(0x40, dataSize) ) ) pointer := create(0, add(data, 0x15), add(dataSize, 0xa)) if iszero(pointer) { mstore(0x00, 0x30116425) revert(0x1c, 0x04) } } } function write(bytes memory data) internal returns (address pointer) { assembly { let originalDataLength := mload(data) let dataSize := add(originalDataLength, DATA_OFFSET) mstore( data, or( 0x61000080600a3d393df300, shl(0x40, dataSize) ) ) pointer := create(0, add(data, 0x15), add(dataSize, 0xa)) if iszero(pointer) { mstore(0x00, 0x30116425) revert(0x1c, 0x04) } } } mstore(data, originalDataLength) function writeDeterministic(bytes memory data, bytes32 salt) internal returns (address pointer) { assembly { let originalDataLength := mload(data) let dataSize := add(originalDataLength, DATA_OFFSET) mstore(data, or(0x61000080600a3d393df300, shl(0x40, dataSize))) pointer := create2(0, add(data, 0x15), add(dataSize, 0xa), salt) if iszero(pointer) { mstore(0x00, 0x30116425) revert(0x1c, 0x04) } } } function writeDeterministic(bytes memory data, bytes32 salt) internal returns (address pointer) { assembly { let originalDataLength := mload(data) let dataSize := add(originalDataLength, DATA_OFFSET) mstore(data, or(0x61000080600a3d393df300, shl(0x40, dataSize))) pointer := create2(0, add(data, 0x15), add(dataSize, 0xa), salt) if iszero(pointer) { mstore(0x00, 0x30116425) revert(0x1c, 0x04) } } } function writeDeterministic(bytes memory data, bytes32 salt) internal returns (address pointer) { assembly { let originalDataLength := mload(data) let dataSize := add(originalDataLength, DATA_OFFSET) mstore(data, or(0x61000080600a3d393df300, shl(0x40, dataSize))) pointer := create2(0, add(data, 0x15), add(dataSize, 0xa), salt) if iszero(pointer) { mstore(0x00, 0x30116425) revert(0x1c, 0x04) } } } mstore(data, originalDataLength) function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) { assembly { let originalDataLength := mload(data) let dataSize := add(originalDataLength, DATA_OFFSET) mstore(data, or(0x61000080600a3d393df300, shl(0x40, dataSize))) hash := keccak256(add(data, 0x15), add(dataSize, 0xa)) mstore(data, originalDataLength) } } function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) { assembly { let originalDataLength := mload(data) let dataSize := add(originalDataLength, DATA_OFFSET) mstore(data, or(0x61000080600a3d393df300, shl(0x40, dataSize))) hash := keccak256(add(data, 0x15), add(dataSize, 0xa)) mstore(data, originalDataLength) } } function predictDeterministicAddress(bytes memory data, bytes32 salt, address deployer) internal pure returns (address predicted) { bytes32 hash = initCodeHash(data); assembly { mstore(0x35, hash) mstore(0x01, shl(96, deployer)) mstore(0x15, salt) predicted := keccak256(0x00, 0x55) mstore(0x35, 0) } } function predictDeterministicAddress(bytes memory data, bytes32 salt, address deployer) internal pure returns (address predicted) { bytes32 hash = initCodeHash(data); assembly { mstore(0x35, hash) mstore(0x01, shl(96, deployer)) mstore(0x15, salt) predicted := keccak256(0x00, 0x55) mstore(0x35, 0) } } function read(address pointer) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), DATA_OFFSET, size) } } function read(address pointer) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), DATA_OFFSET, size) } } function read(address pointer) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), DATA_OFFSET, size) } } let size := sub(pointerCodesize, DATA_OFFSET) data := mload(0x40) function read(address pointer, uint256 start) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } if iszero(gt(pointerCodesize, start)) { mstore(0x00, 0x84eb0dd1) revert(0x1c, 0x04) } let size := sub(pointerCodesize, add(start, DATA_OFFSET)) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), add(start, DATA_OFFSET), size) } } function read(address pointer, uint256 start) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } if iszero(gt(pointerCodesize, start)) { mstore(0x00, 0x84eb0dd1) revert(0x1c, 0x04) } let size := sub(pointerCodesize, add(start, DATA_OFFSET)) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), add(start, DATA_OFFSET), size) } } function read(address pointer, uint256 start) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } if iszero(gt(pointerCodesize, start)) { mstore(0x00, 0x84eb0dd1) revert(0x1c, 0x04) } let size := sub(pointerCodesize, add(start, DATA_OFFSET)) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), add(start, DATA_OFFSET), size) } } function read(address pointer, uint256 start) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } if iszero(gt(pointerCodesize, start)) { mstore(0x00, 0x84eb0dd1) revert(0x1c, 0x04) } let size := sub(pointerCodesize, add(start, DATA_OFFSET)) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), add(start, DATA_OFFSET), size) } } data := mload(0x40) function read(address pointer, uint256 start, uint256 end) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } and( ) ) { mstore(0x00, 0x84eb0dd1) revert(0x1c, 0x04) } let size := sub(end, start) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), add(start, DATA_OFFSET), size) } } function read(address pointer, uint256 start, uint256 end) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } and( ) ) { mstore(0x00, 0x84eb0dd1) revert(0x1c, 0x04) } let size := sub(end, start) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), add(start, DATA_OFFSET), size) } } function read(address pointer, uint256 start, uint256 end) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } and( ) ) { mstore(0x00, 0x84eb0dd1) revert(0x1c, 0x04) } let size := sub(end, start) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), add(start, DATA_OFFSET), size) } } if iszero( function read(address pointer, uint256 start, uint256 end) internal view returns (bytes memory data) { assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { mstore(0x00, 0x11052bb4) revert(0x1c, 0x04) } and( ) ) { mstore(0x00, 0x84eb0dd1) revert(0x1c, 0x04) } let size := sub(end, start) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) extcodecopy(pointer, add(data, 0x20), add(start, DATA_OFFSET), size) } } data := mload(0x40) }
4,969,604
[ 1, 1994, 471, 1045, 358, 9195, 2502, 622, 279, 8330, 434, 326, 6991, 18, 225, 348, 355, 361, 93, 261, 4528, 2207, 6662, 18, 832, 19, 7737, 1235, 19, 18281, 81, 361, 93, 19, 10721, 19, 5254, 19, 4816, 19, 5471, 19, 55, 13651, 22, 18, 18281, 13, 225, 348, 2219, 17, 2586, 17, 464, 17, 50, 3145, 1385, 261, 4528, 2207, 6662, 18, 832, 19, 55, 2219, 17, 2586, 17, 464, 17, 50, 3145, 1385, 13, 225, 21154, 628, 348, 355, 81, 340, 261, 4528, 2207, 6662, 18, 832, 19, 2338, 7300, 2499, 19, 18281, 81, 340, 19, 10721, 19, 5254, 19, 4816, 19, 5471, 19, 55, 13651, 22, 18, 18281, 13, 225, 21154, 628, 374, 92, 4021, 261, 4528, 2207, 6662, 18, 832, 19, 20, 92, 4021, 19, 87, 2233, 22, 19, 10721, 19, 7525, 19, 16351, 87, 19, 55, 13651, 22, 18, 18281, 13, 2, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 ]
[ 1, 12083, 348, 13651, 22, 288, 203, 203, 565, 2254, 5034, 2713, 5381, 8730, 67, 11271, 273, 404, 31, 203, 203, 203, 565, 555, 8587, 2925, 5621, 203, 203, 565, 555, 1962, 4926, 5621, 203, 203, 565, 555, 2720, 11224, 5694, 5621, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 445, 1045, 12, 3890, 3778, 501, 13, 2713, 1135, 261, 2867, 4407, 13, 288, 203, 3639, 19931, 288, 203, 5411, 2231, 2282, 751, 1782, 519, 312, 945, 12, 892, 13, 203, 203, 5411, 2231, 30216, 519, 527, 12, 8830, 751, 1782, 16, 8730, 67, 11271, 13, 203, 203, 5411, 312, 2233, 12, 203, 7734, 501, 16, 203, 7734, 578, 12, 203, 10792, 374, 92, 9498, 2787, 3672, 28133, 69, 23, 72, 5520, 23, 2180, 19249, 16, 203, 10792, 699, 80, 12, 20, 92, 7132, 16, 30216, 13, 203, 7734, 262, 203, 5411, 262, 203, 203, 5411, 4407, 519, 752, 12, 20, 16, 527, 12, 892, 16, 374, 92, 3600, 3631, 527, 12, 892, 1225, 16, 374, 6995, 3719, 203, 203, 5411, 309, 353, 7124, 12, 10437, 13, 288, 203, 7734, 312, 2233, 12, 20, 92, 713, 16, 374, 92, 31831, 23147, 2947, 13, 203, 7734, 15226, 12, 20, 92, 21, 71, 16, 374, 92, 3028, 13, 203, 5411, 289, 203, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 1045, 12, 3890, 3778, 501, 13, 2713, 1135, 261, 2867, 4407, 13, 288, 203, 3639, 19931, 288, 203, 5411, 2231, 2282, 751, 1782, 519, 312, 945, 12, 2 ]
//SPDX-License-Identifier: Unlicense pragma solidity 0.7.5; pragma abicoder v2; import './interfaces/IFxMessageProcessor.sol'; import './BridgeExecutorBase.sol'; contract PolygonBridgeExecutor is BridgeExecutorBase, IFxMessageProcessor { address private _fxRootSender; address private _fxChild; event FxRootSenderUpdate(address previousFxRootSender, address newFxRootSender); event FxChildUpdate(address previousFxChild, address newFxChild); modifier onlyFxChild() { require(msg.sender == _fxChild, 'UNAUTHORIZED_CHILD_ORIGIN'); _; } constructor( address fxRootSender, address fxChild, uint256 delay, uint256 gracePeriod, uint256 minimumDelay, uint256 maximumDelay, address guardian ) BridgeExecutorBase(delay, gracePeriod, minimumDelay, maximumDelay, guardian) { _fxRootSender = fxRootSender; _fxChild = fxChild; } /// @inheritdoc IFxMessageProcessor function processMessageFromRoot( uint256 stateId, address rootMessageSender, bytes calldata data ) external override onlyFxChild { require(rootMessageSender == _fxRootSender, 'UNAUTHORIZED_ROOT_ORIGIN'); address[] memory targets; uint256[] memory values; string[] memory signatures; bytes[] memory calldatas; bool[] memory withDelegatecalls; (targets, values, signatures, calldatas, withDelegatecalls) = abi.decode( data, (address[], uint256[], string[], bytes[], bool[]) ); _queue(targets, values, signatures, calldatas, withDelegatecalls); } /** * @dev Update the expected address of contract originating a cross-chain tranasaction * @param fxRootSender contract originating a cross-chain tranasaction - likely the aave governance executor **/ function updateFxRootSender(address fxRootSender) external onlyThis { emit FxRootSenderUpdate(_fxRootSender, fxRootSender); _fxRootSender = fxRootSender; } /** * @dev Update the address of the FxChild contract * @param fxChild the address of the contract used to foward cross-chain transactions on Polygon **/ function updateFxChild(address fxChild) external onlyThis { emit FxChildUpdate(_fxChild, fxChild); _fxChild = fxChild; } /** * @dev Get the address currently stored as fxRootSender * @return fxRootSender contract originating a cross-chain tranasaction - likely the aave governance executor **/ function getFxRootSender() external view returns (address) { return _fxRootSender; } /** * @dev Get the address currently stored as fxChild * @return fxChild the address of the contract used to foward cross-chain transactions on Polygon **/ function getFxChild() external view returns (address) { return _fxChild; } }
* @dev Update the address of the FxChild contract @param fxChild the address of the contract used to foward cross-chain transactions on Polygon/
function updateFxChild(address fxChild) external onlyThis { emit FxChildUpdate(_fxChild, fxChild); _fxChild = fxChild; }
12,737,126
[ 1, 1891, 326, 1758, 434, 326, 478, 92, 1763, 6835, 225, 12661, 1763, 326, 1758, 434, 326, 6835, 1399, 358, 284, 543, 1060, 6828, 17, 5639, 8938, 603, 12681, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 42, 92, 1763, 12, 2867, 12661, 1763, 13, 3903, 1338, 2503, 288, 203, 565, 3626, 478, 92, 1763, 1891, 24899, 19595, 1763, 16, 12661, 1763, 1769, 203, 565, 389, 19595, 1763, 273, 12661, 1763, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x9773Db56d3c34F2a1b8aDA34aA370BE2d2d9E467/sources/project_/contracts/DistrictPower.sol
used for easily retrieve the referrer tree structure from front-end 用于从前端轻松检索引用者树结构
mapping(address => address[]) public children;
835,009
[ 1, 3668, 364, 17997, 4614, 326, 14502, 2151, 3695, 628, 6641, 17, 409, 225, 168, 247, 106, 165, 123, 241, 165, 124, 241, 166, 236, 240, 168, 109, 112, 169, 126, 124, 167, 256, 127, 167, 101, 227, 168, 117, 100, 166, 125, 248, 168, 247, 106, 169, 227, 232, 167, 259, 244, 168, 124, 246, 167, 257, 231, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 1758, 63, 5717, 1071, 2325, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0x6D1Ba393ED7e26F4934746B3e82202F0eDf9563D/sources/contracts/mixins/0xcert/nf-token.sol
* @dev Transfers the ownership of an NFT from one address to another address. This function can be changed to payable. @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. @param from The current owner of the NFT. @param to The new owner. @param tokenId The NFT to transfer. @param data Additional data with no specified format, sent in call to `_to`./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external override { _safeTransferFrom(from, to, tokenId, data); }
16,848,414
[ 1, 1429, 18881, 326, 23178, 434, 392, 423, 4464, 628, 1245, 1758, 358, 4042, 1758, 18, 1220, 445, 848, 506, 3550, 358, 8843, 429, 18, 225, 22435, 3308, 1375, 3576, 18, 15330, 68, 353, 326, 783, 3410, 16, 392, 10799, 3726, 16, 578, 326, 20412, 1758, 364, 333, 423, 4464, 18, 22435, 309, 1375, 67, 2080, 68, 353, 486, 326, 783, 3410, 18, 22435, 309, 1375, 67, 869, 68, 353, 326, 3634, 1758, 18, 22435, 309, 1375, 67, 2316, 548, 68, 353, 486, 279, 923, 423, 4464, 18, 5203, 7412, 353, 3912, 16, 333, 445, 4271, 309, 1375, 67, 869, 68, 353, 279, 13706, 6835, 261, 710, 963, 405, 374, 2934, 971, 1427, 16, 518, 4097, 1375, 265, 654, 39, 27, 5340, 8872, 68, 603, 1375, 67, 869, 68, 471, 1216, 309, 326, 327, 460, 353, 486, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 654, 39, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 4183, 5912, 1265, 12, 203, 565, 1758, 628, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 1147, 548, 16, 203, 565, 1731, 745, 892, 501, 203, 225, 262, 3903, 3849, 288, 203, 565, 389, 4626, 5912, 1265, 12, 2080, 16, 358, 16, 1147, 548, 16, 501, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xeCb83393F24375D8eC121A1C977f64b96c85A47C/sources/Goldereum.sol
import "../IERC20.sol"; */
interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
9,757,665
[ 1, 5666, 315, 6216, 45, 654, 39, 3462, 18, 18281, 14432, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 2277, 353, 467, 654, 39, 3462, 288, 203, 203, 565, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 15105, 1435, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x91C1842E87dE6fCc81b2a83e31Da00345e95059D/sources/contracts/PartyBidRA.sol
* Vote for a new Zora bid proposal if you have not already/ Ensure that caller is a DAO member Ensure that caller has not already voted in favor of proposal Increment aggregate support with power(voter) Update supporters mapping
function DAOVoteForZoraBidProposal(uint256 _proposalId) external onlyIfAuctionWon() { require(daoStakes[msg.sender] > 0, "PartyBid: Must be a DAO member to vote for bid proposal."); require(BidProposalSupporters[_proposalId][msg.sender] != true, "PartyBid: Cannot vote for a proposal twice."); BidProposals[_proposalId].aggregateSupport = BidProposals[_proposalId].aggregateSupport.add(daoStakes[msg.sender]); BidProposalSupporters[_proposalId][msg.sender] = true; }
3,220,152
[ 1, 19338, 364, 279, 394, 2285, 10610, 9949, 14708, 309, 1846, 1240, 486, 1818, 19, 7693, 716, 4894, 353, 279, 463, 20463, 3140, 7693, 716, 4894, 711, 486, 1818, 331, 16474, 316, 18552, 434, 14708, 17883, 7047, 2865, 598, 7212, 12, 90, 20005, 13, 2315, 1169, 3831, 5432, 2874, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 463, 20463, 19338, 1290, 62, 10610, 17763, 14592, 12, 11890, 5034, 389, 685, 8016, 548, 13, 3903, 1338, 2047, 37, 4062, 59, 265, 1435, 288, 203, 565, 2583, 12, 2414, 83, 510, 3223, 63, 3576, 18, 15330, 65, 405, 374, 16, 315, 17619, 17763, 30, 6753, 506, 279, 463, 20463, 3140, 358, 12501, 364, 9949, 14708, 1199, 1769, 203, 565, 2583, 12, 17763, 14592, 3088, 3831, 5432, 63, 67, 685, 8016, 548, 6362, 3576, 18, 15330, 65, 480, 638, 16, 315, 17619, 17763, 30, 14143, 12501, 364, 279, 14708, 13605, 1199, 1769, 203, 203, 565, 605, 350, 626, 22536, 63, 67, 685, 8016, 548, 8009, 18573, 6289, 273, 605, 350, 626, 22536, 63, 67, 685, 8016, 548, 8009, 18573, 6289, 18, 1289, 12, 2414, 83, 510, 3223, 63, 3576, 18, 15330, 19226, 203, 203, 565, 605, 350, 14592, 3088, 3831, 5432, 63, 67, 685, 8016, 548, 6362, 3576, 18, 15330, 65, 273, 638, 31, 203, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-14 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // This is a special "passive" migration contract of MTM. // Every single method is modified and has custom "passive" migration proxy logic. abstract contract Ownable { address public owner; constructor() { owner = msg.sender; } modifier onlyOwner { require(owner == msg.sender, "Ownable: NO"); _; } function transferOwnership(address newOwner_) public virtual onlyOwner { owner = newOwner_; } } interface iCM { // Views function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function ownerOf(uint256 tokenId_) external view returns (address); function balanceOf(address address_) external view returns (uint256); function getApproved(uint256 tokenId_) external view returns (address); function isApprovedForAll(address owner_, address operator_) external view returns (bool); } // ERC721I Functions, but we modified it for passive migration method // ERC721IMigrator uses local state storage for gas savings. // It is like ERC721IStorage and ERC721IOperator combined into one. contract ERC721IMigrator is Ownable { // Interface the MTM Characters Main V1 iCM public CM; function setCM(address address_) external onlyOwner { CM = iCM(address_); } // Name and Symbol Stuff string public name; string public symbol; constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } // We turned these to _ prefix so we can use a override function // To display custom proxy and passive migration logic uint256 public totalSupply; mapping(uint256 => address) public _ownerOf; mapping(address => uint256) public _balanceOf; // Here we have to keep track of a initialized balanceOf to prevent any view issues mapping(address => bool) public _balanceOfInitialized; // We disregard the previous contract's approvals mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; // // TotalSupply Setter // Here, we set the totalSupply to equal the previous function setTotalSupply(uint256 totalSupply_) external onlyOwner { totalSupply = totalSupply_; } // // Initializer // This is a custom Transfer emitter for the initialize of this contract only function initialize(uint256[] calldata tokenIds_, address[] calldata owners_) external onlyOwner { require(tokenIds_.length == owners_.length, "initialize(): array length mismatch!"); for (uint256 i = 0; i < tokenIds_.length; i++) { emit Transfer(address(0x0), owners_[i], tokenIds_[i]); } } // OwnerOf (Proxy View) function ownerOf(uint256 tokenId_) public view returns (address) { // Find out of the _ownerOf slot has been initialized. // We hardcode the tokenId_ to save gas. if (tokenId_ <= 3259 && _ownerOf[tokenId_] == address(0x0)) { // _ownerOf[tokenId_] is not initialized yet, so return the CM V1 value. return CM.ownerOf(tokenId_); } else { // If it is already initialized, or is higher than migration Id // return local state storage instead. return _ownerOf[tokenId_]; } } // BalanceOf (Proxy View) function balanceOf(address address_) public view returns (uint256) { // Proxy the balance function // We have a tracker of initialization of _balanceOf to track the differences // If initialized, we use the state storage. Otherwise, we use CM V1 storage. if (_balanceOfInitialized[address_]) { return _balanceOf[address_]; } else { return CM.balanceOf(address_); } } // Events! L[o_o]⅃ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Mint(address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); // Functions function _mint(address to_, uint256 tokenId_) internal virtual { require(to_ != address(0x0), "ERC721IMigrator: _mint() Mint to Zero Address!"); require(ownerOf(tokenId_) == address(0x0), "ERC721IMigrator: _mint() Token already Exists!"); // // ERC721I Logic // We set _ownerOf in a normal way _ownerOf[tokenId_] = to_; // We rebalance the _balanceOf on initialization, otherwise follow normal ERC721I logic if (_balanceOfInitialized[to_]) { // If we are already initialized _balanceOf[to_]++; } else { _balanceOf[to_] = (CM.balanceOf(to_) + 1); _balanceOfInitialized[to_] = true; } // Increment TotalSupply as normal totalSupply++; // // ERC721I Logic End // Emit Events emit Transfer(address(0x0), to_, tokenId_); emit Mint(to_, tokenId_); } function _transfer(address from_, address to_, uint256 tokenId_) internal virtual { require(from_ == ownerOf(tokenId_), "ERC721IMigrator: _transfer() Transfer from_ != ownerOf(tokenId_)"); require(to_ != address(0x0), "ERC721IMigrator: _transfer() Transfer to Zero Address!"); // // ERC721I Transfer Logic // If token has an approval if (getApproved[tokenId_] != address(0x0)) { // Remove the outstanding approval getApproved[tokenId_] = address(0x0); } // Set the _ownerOf to the receiver _ownerOf[tokenId_] = to_; // // Initialize and Rebalance _balanceOf if (_balanceOfInitialized[from_]) { // If from_ is initialized, do normal balance change _balanceOf[from_]--; } else { // If from_ is NOT initialized, follow rebalance flow _balanceOf[from_] = (CM.balanceOf(from_) - 1); // Set from_ as initialized _balanceOfInitialized[from_] = true; } if (_balanceOfInitialized[to_]) { // If to_ is initialized, do normal balance change _balanceOf[to_]++; } else { // If to_ is NOT initialized, follow rebalance flow _balanceOf[to_] = (CM.balanceOf(to_) + 1); // Set to_ as initialized; _balanceOfInitialized[to_] = true; } // // ERC721I Transfer Logic End emit Transfer(from_, to_, tokenId_); } // Approvals function _approve(address to_, uint256 tokenId_) internal virtual { if (getApproved[tokenId_] != to_) { getApproved[tokenId_] = to_; emit Approval(ownerOf(tokenId_), to_, tokenId_); } } function _setApprovalForAll(address owner_, address operator_, bool approved_) internal virtual { require(owner_ != operator_, "ERC721IMigrator: _setApprovalForAll() Owner must not be the Operator!"); isApprovedForAll[owner_][operator_] = approved_; emit ApprovalForAll(owner_, operator_, approved_); } // // Functional Internal Views function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view returns (bool) { address _owner = ownerOf(tokenId_); require(_owner != address(0x0), "ERC721IMigrator: _isApprovedOrOwner() Owner is Zero Address!"); return (spender_ == _owner // is the owner OR || spender_ == getApproved[tokenId_] // is approved for token OR || isApprovedForAll[_owner][spender_] // isApprovedForAll spender ); } // Exists function _exists(uint256 tokenId_) internal view virtual returns (bool) { // We hardcode tokenId_ for gas savings if (tokenId_ <= 3259) { return true; } return _ownerOf[tokenId_] != address(0x0); } // Public Write Functions function approve(address to_, uint256 tokenId_) public virtual { address _owner = ownerOf(tokenId_); require(to_ != _owner, "ERC721IMigrator: approve() cannot approve owner!"); require(msg.sender == _owner // sender is the owner of the token || isApprovedForAll[_owner][msg.sender], // or isApprovedForAll for the owner "ERC721IMigrator: approve() Caller is not owner of isApprovedForAll!"); _approve(to_, tokenId_); } // SetApprovalForAll - the msg.sender is always the subject of approval function setApprovalForAll(address operator_, bool approved_) public virtual { _setApprovalForAll(msg.sender, operator_, approved_); } // Transfers function transferFrom(address from_, address to_, uint256 tokenId_) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721IMigrator: transferFrom() _isApprovedOrOwner = false!"); _transfer(from_, to_, tokenId_); } function safeTransferFrom(address from_, address to_, uint256 tokenId_, bytes memory data_) public virtual { transferFrom(from_, to_, tokenId_); if (to_.code.length != 0) { (, bytes memory _returned) = to_.staticcall(abi.encodeWithSelector(0x150b7a02, msg.sender, from_, tokenId_, data_)); bytes4 _selector = abi.decode(_returned, (bytes4)); require(_selector == 0x150b7a02, "ERC721IMigrator: safeTransferFrom() to_ not ERC721Receivable!"); } } function safeTransferFrom(address from_, address to_, uint256 tokenId_) public virtual { safeTransferFrom(from_, to_, tokenId_, ""); } // Native Multi-Transfers by 0xInuarashi function multiTransferFrom(address from_, address to_, uint256[] memory tokenIds_) public virtual { for (uint256 i = 0; i < tokenIds_.length; i++) { transferFrom(from_, to_, tokenIds_[i]); } } function multiSafeTransferFrom(address from_, address to_, uint256[] memory tokenIds_, bytes memory data_) public virtual { for (uint256 i = 0; i < tokenIds_.length; i++ ){ safeTransferFrom(from_, to_, tokenIds_[i], data_); } } // OZ Standard Stuff function supportsInterface(bytes4 interfaceId_) public pure returns (bool) { return (interfaceId_ == 0x80ac58cd || interfaceId_ == 0x5b5e139f); } // High Gas Loop View Functions function walletOfOwner(address address_) public virtual view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[](_balance); uint256 _index; uint256 _loopThrough = totalSupply; for (uint256 i = 0; i < _loopThrough; i++) { // Add another loop through for each 0x0 until array is filled if (ownerOf(i) == address(0x0) && _tokens[_balance - 1] == 0) { _loopThrough++; } // Fill the array on each token found if (ownerOf(i) == address_) { // Record the ID in the index _tokens[_index] = i; // Increment the index _index++; } } return _tokens; } // TokenURIs Functions Omitted // } interface IERC721 { function ownerOf(uint256 tokenId_) external view returns (address); function transferFrom(address from_, address to_, uint256 tokenId_) external; } interface iCS { struct Character { uint8 race_; uint8 renderType_; uint16 transponderId_; uint16 spaceCapsuleId_; uint8 augments_; uint16 basePoints_; uint16 totalEquipmentBonus_; } struct Stats { uint8 strength_; uint8 agility_; uint8 constitution_; uint8 intelligence_; uint8 spirit_; } struct Equipment { uint8 weaponUpgrades_; uint8 chestUpgrades_; uint8 headUpgrades_; uint8 legsUpgrades_; uint8 vehicleUpgrades_; uint8 armsUpgrades_; uint8 artifactUpgrades_; uint8 ringUpgrades_; } // Create Character function createCharacter(uint tokenId_, Character memory Character_) external; // Characters function setName(uint256 tokenId_, string memory name_) external; function setRace(uint256 tokenId_, string memory race_) external; function setRenderType(uint256 tokenId_, uint8 renderType_) external; function setTransponderId(uint256 tokenId_, uint16 transponderId_) external; function setSpaceCapsuleId(uint256 tokenId_, uint16 spaceCapsuleId_) external; function setAugments(uint256 tokenId_, uint8 augments_) external; function setBasePoints(uint256 tokenId_, uint16 basePoints_) external; function setBaseEquipmentBonus(uint256 tokenId_, uint16 baseEquipmentBonus_) external; function setTotalEquipmentBonus(uint256 tokenId_, uint16 totalEquipmentBonus) external; // Stats function setStrength(uint256 tokenId_, uint8 strength_) external; function setAgility(uint256 tokenId_, uint8 agility_) external; function setConstitution(uint256 tokenId_, uint8 constitution_) external; function setIntelligence(uint256 tokenId_, uint8 intelligence_) external; function setSpirit(uint256 tokenId_, uint8 spirit_) external; // Equipment function setWeaponUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setChestUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setHeadUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setLegsUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setVehicleUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setArmsUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setArtifactUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setRingUpgrades(uint256 tokenId_, uint8 upgrade_) external; // Structs and Mappings function names(uint256 tokenId_) external view returns (string memory); function characters(uint256 tokenId_) external view returns (Character memory); function stats(uint256 tokenId_) external view returns (Stats memory); function equipments(uint256 tokenId_) external view returns (Equipment memory); function contractToRace(address contractAddress_) external view returns (uint8); } interface iCC { function queryCharacterYieldRate(uint8 augments_, uint16 basePoints_, uint16 totalEquipmentBonus_) external view returns (uint256); function getEquipmentBaseBonus(uint16 spaceCapsuleId_) external view returns (uint16); } interface iMES { // View Functions function balanceOf(address address_) external view returns (uint256); function pendingRewards(address address_) external view returns (uint256); // Administration function setYieldRate(address address_, uint256 yieldRate_) external; function addYieldRate(address address_, uint256 yieldRateAdd_) external; function subYieldRate(address address_, uint256 yieldRateSub_) external; // Credits System function deductCredits(address address_, uint256 amount_) external; function addCredits(address address_, uint256 amount_) external; // Claiming function updateReward(address address_) external; function burn(address from, uint256 amount_) external; } interface iMetadata { function renderMetadata(uint256 tokenId_) external view returns (string memory); } contract MTMCharacters is ERC721IMigrator { constructor() ERC721IMigrator("MTM Characters", "CHARACTERS") {} // Interfaces iCS public CS; iCC public CC; iMES public MES; iMetadata public Metadata; IERC721 public TP; IERC721 public SC; function setContracts(address metadata_, address cc_, address cs_, address mes_, address tp_, address sc_) external onlyOwner { CS = iCS(cs_); CC = iCC(cc_); MES = iMES(mes_); Metadata = iMetadata(metadata_); TP = IERC721(tp_); SC = IERC721(sc_); } // Mappings mapping(address => mapping(uint256 => bool)) public contractAddressToTokenUploaded; // Internal Write Functions function __yieldMintHook(address to_, uint256 tokenId_) internal { // First, we update the reward. MES.updateReward(to_); // Then, we query the token yield rate. iCS.Character memory _Character = CS.characters(tokenId_); uint256 _tokenYieldRate = CC.queryCharacterYieldRate(_Character.augments_, _Character.basePoints_, _Character.totalEquipmentBonus_); // Lastly, we adjust the yield rate of the address. MES.addYieldRate(to_, _tokenYieldRate); } function __yieldTransferHook(address from_, address to_, uint256 tokenId_) internal { // First, we update the reward. MES.updateReward(from_); MES.updateReward(to_); // Then, we query the token yield rate. iCS.Character memory _Character = CS.characters(tokenId_); uint256 _tokenYieldRate = CC.queryCharacterYieldRate(_Character.augments_, _Character.basePoints_, _Character.totalEquipmentBonus_); // Lastly, we adjust the yield rate of the addresses. MES.subYieldRate(from_, _tokenYieldRate); MES.addYieldRate(to_, _tokenYieldRate); } // Public Write Functions mapping(uint8 => bool) public renderTypeAllowed; function setRenderTypeAllowed(uint8 renderType_, bool bool_) external onlyOwner { renderTypeAllowed[renderType_] = bool_; } function beamCharacter(uint256 transponderId_, uint256 spaceCapsuleId_, uint8 renderType_) public { require(msg.sender == TP.ownerOf(transponderId_) && msg.sender == SC.ownerOf(spaceCapsuleId_), "Unowned pair!"); require(renderTypeAllowed[renderType_], "This render type is not allowed!"); // Burn the Transponder and Space Capsule. TP.transferFrom(msg.sender, address(this), transponderId_); SC.transferFrom(msg.sender, address(this), spaceCapsuleId_); uint8 _race = uint8( (uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, transponderId_, spaceCapsuleId_))) % 10) + 1 ); // RNG (1-10) uint16 _equipmentBonus = CC.getEquipmentBaseBonus((uint16(spaceCapsuleId_))); iCS.Character memory _Character = iCS.Character( _race, renderType_, uint16(transponderId_), uint16(spaceCapsuleId_), 0, 0, _equipmentBonus ); CS.createCharacter(totalSupply, _Character); __yieldMintHook(msg.sender, totalSupply); _mint(msg.sender, totalSupply); } function uploadCharacter(uint256 transponderId_, uint256 spaceCapsuleId_, uint8 renderType_, address contractAddress_, uint256 uploadId_) public { require(msg.sender == TP.ownerOf(transponderId_) && msg.sender == SC.ownerOf(spaceCapsuleId_), "Unowned pair!"); require(msg.sender == IERC721(contractAddress_).ownerOf(uploadId_), "You don't own this character!"); require(!contractAddressToTokenUploaded[contractAddress_][uploadId_], "This character has already been uploaded!"); require(renderTypeAllowed[renderType_], "This render type is not allowed!"); // Burn the Transponder and Space Capsule. Then, set the character as uploaded. TP.transferFrom(msg.sender, address(this), transponderId_); SC.transferFrom(msg.sender, address(this), spaceCapsuleId_); contractAddressToTokenUploaded[contractAddress_][uploadId_] = true; uint8 _race = CS.contractToRace(contractAddress_); uint16 _equipmentBonus = CC.getEquipmentBaseBonus((uint16(spaceCapsuleId_))); iCS.Character memory _Character = iCS.Character( _race, renderType_, uint16(transponderId_), uint16(spaceCapsuleId_), 0, 0, _equipmentBonus ); CS.createCharacter(totalSupply, _Character); __yieldMintHook(msg.sender, totalSupply); _mint(msg.sender, totalSupply); } // Public Write Multi-Functions function multiBeamCharacter(uint256[] memory transponderIds_, uint256[] memory spaceCapsuleIds_, uint8[] memory renderTypes_) public { require(transponderIds_.length == spaceCapsuleIds_.length, "Missing pairs!"); require(transponderIds_.length == renderTypes_.length, "Missing render type!"); for (uint256 i = 0; i < transponderIds_.length; i++) { beamCharacter(transponderIds_[i], spaceCapsuleIds_[i], renderTypes_[i]); } } function multiUploadCharacter(uint256[] memory transponderIds_, uint256[] memory spaceCapsuleIds_, uint8[] memory renderTypes_, address contractAddress_, uint256[] memory uploadIds_) public { require(transponderIds_.length == spaceCapsuleIds_.length, "Missing pairs!"); require(transponderIds_.length == renderTypes_.length, "Missing render type!"); require(transponderIds_.length == uploadIds_.length, "Upload IDs mismatched length!"); for (uint256 i = 0; i < transponderIds_.length; i++) { uploadCharacter(transponderIds_[i], spaceCapsuleIds_[i], renderTypes_[i], contractAddress_, uploadIds_[i]); } } // Transfer Hooks function transferFrom(address from_, address to_, uint256 tokenId_) public override { __yieldTransferHook(from_, to_, tokenId_); ERC721IMigrator.transferFrom(from_, to_, tokenId_); } function safeTransferFrom(address from_, address to_, uint256 tokenId_, bytes memory bytes_) public override { __yieldTransferHook(from_, to_, tokenId_); ERC721IMigrator.safeTransferFrom(from_, to_, tokenId_, bytes_); } // Public View Functions function tokenURI(uint256 tokenId_) public view returns (string memory) { require(_exists(tokenId_), "Character does not exist!"); return Metadata.renderMetadata(tokenId_); } }
Burn the Transponder and Space Capsule. Then, set the character as uploaded.
function uploadCharacter(uint256 transponderId_, uint256 spaceCapsuleId_, uint8 renderType_, address contractAddress_, uint256 uploadId_) public { require(msg.sender == TP.ownerOf(transponderId_) && msg.sender == SC.ownerOf(spaceCapsuleId_), "Unowned pair!"); require(msg.sender == IERC721(contractAddress_).ownerOf(uploadId_), "You don't own this character!"); require(!contractAddressToTokenUploaded[contractAddress_][uploadId_], "This character has already been uploaded!"); require(renderTypeAllowed[renderType_], "This render type is not allowed!"); TP.transferFrom(msg.sender, address(this), transponderId_); SC.transferFrom(msg.sender, address(this), spaceCapsuleId_); contractAddressToTokenUploaded[contractAddress_][uploadId_] = true; uint8 _race = CS.contractToRace(contractAddress_); uint16 _equipmentBonus = CC.getEquipmentBaseBonus((uint16(spaceCapsuleId_))); iCS.Character memory _Character = iCS.Character( _race, renderType_, uint16(transponderId_), uint16(spaceCapsuleId_), 0, 0, _equipmentBonus ); CS.createCharacter(totalSupply, _Character); __yieldMintHook(msg.sender, totalSupply); _mint(msg.sender, totalSupply); }
7,751,947
[ 1, 38, 321, 326, 2604, 17707, 471, 14059, 385, 6679, 725, 18, 9697, 16, 444, 326, 3351, 487, 9140, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3617, 7069, 12, 11890, 5034, 906, 17707, 548, 67, 16, 2254, 5034, 3476, 24193, 725, 548, 67, 16, 2254, 28, 1743, 559, 67, 16, 1758, 6835, 1887, 67, 16, 2254, 5034, 3617, 548, 67, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 26878, 18, 8443, 951, 12, 2338, 17707, 548, 67, 13, 597, 1234, 18, 15330, 422, 8795, 18, 8443, 951, 12, 2981, 24193, 725, 548, 67, 3631, 315, 984, 995, 329, 3082, 4442, 1769, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 467, 654, 39, 27, 5340, 12, 16351, 1887, 67, 2934, 8443, 951, 12, 6327, 548, 67, 3631, 315, 6225, 2727, 1404, 4953, 333, 3351, 4442, 1769, 203, 3639, 2583, 12, 5, 16351, 1887, 774, 1345, 24585, 63, 16351, 1887, 67, 6362, 6327, 548, 67, 6487, 315, 2503, 3351, 711, 1818, 2118, 9140, 4442, 1769, 203, 3639, 2583, 12, 5902, 559, 5042, 63, 5902, 559, 67, 6487, 315, 2503, 1743, 618, 353, 486, 2935, 4442, 1769, 203, 203, 3639, 26878, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 906, 17707, 548, 67, 1769, 203, 3639, 8795, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3476, 24193, 725, 548, 67, 1769, 203, 3639, 6835, 1887, 774, 1345, 24585, 63, 16351, 1887, 67, 6362, 6327, 548, 67, 65, 273, 638, 31, 203, 203, 3639, 2254, 28, 389, 9963, 273, 6761, 18, 16351, 774, 54, 623, 12, 16351, 1887, 67, 1769, 203, 3639, 2254, 2313, 389, 14298, 11568, 38, 22889, 273, 16525, 2 ]
pragma solidity ^0.5; /* NOTE: @kleros/kleros-interraction is not compatible with this solc version */ /* NOTE: I put all the arbitration files in the same file because the dependancy between the different contracts is a real "headache" */ /* If someone takes up the challenge, a PR is welcome */ /** * @title CappedMath * @dev Math operations with caps for under and overflow. * NOTE: see https://raw.githubusercontent.com/kleros/kleros-interaction/master/contracts/libraries/CappedMath.sol */ library CappedMath { uint constant private UINT_MAX = 2**256 - 1; /** * @dev Adds two unsigned integers, returns 2^256 - 1 on overflow. */ function addCap(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; return c >= _a ? c : UINT_MAX; } /** * @dev Subtracts two integers, returns 0 on underflow. */ function subCap(uint _a, uint _b) internal pure returns (uint) { if (_b > _a) return 0; else return _a - _b; } /** * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow. */ function mulCap(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-solidity/pull/522 if (_a == 0) return 0; uint c = _a * _b; return c / _a == _b ? c : UINT_MAX; } } /** @title IArbitrable * Arbitrable interface. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ interface IArbitrable { /** @dev To be emmited when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); /** @dev To be emmited when a dispute is created to link the correct meta-evidence to the disputeID * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute. */ event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID); /** @dev To be raised when evidence are submitted. Should point to the ressource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence(Arbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence); /** @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external; } /** @title Arbitrable * Arbitrable abstract contract. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ contract Arbitrable is IArbitrable { Arbitrator public arbitrator; bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour. /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. */ constructor(Arbitrator _arbitrator, bytes memory _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { emit Ruling(Arbitrator(msg.sender), _disputeID, _ruling); executeRuling(_disputeID, _ruling); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal; } /** @title Arbitrator * Arbitrator abstract contract. * When developing arbitrator contracts we need to: * -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, use nbDisputes). * -Define the functions for cost display (arbitrationCost and appealCost). * -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling). */ contract Arbitrator { enum DisputeStatus {Waiting, Appealable, Solved} modifier requireArbitrationFee(bytes memory _extraData) { require(msg.value >= arbitrationCost(_extraData), "Not enough ETH to cover arbitration costs."); _; } modifier requireAppealFee(uint _disputeID, bytes memory _extraData) { require(msg.value >= appealCost(_disputeID, _extraData), "Not enough ETH to cover appeal costs."); _; } /** @dev To be raised when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when a dispute can be appealed. * @param _disputeID ID of the dispute. */ event AppealPossible(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes memory _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function arbitrationCost(bytes memory _extraData) public view returns(uint fee); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes memory _extraData) public requireAppealFee(_disputeID,_extraData) payable { emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint fee); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) {} /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) public view returns(uint ruling); } /** @title Centralized Arbitrator * @dev This is a centralized arbitrator deciding alone on the result of disputes. No appeals are possible. */ contract CentralizedArbitrator is Arbitrator { address public owner = msg.sender; uint arbitrationPrice; // Not public because arbitrationCost already acts as an accessor. uint constant NOT_PAYABLE_VALUE = (2**256-2)/2; // High value to be sure that the appeal is too expensive. struct DisputeStruct { Arbitrable arbitrated; uint choices; uint fee; uint ruling; DisputeStatus status; } modifier onlyOwner {require(msg.sender==owner, "Can only be called by the owner."); _;} DisputeStruct[] public disputes; /** @dev Constructor. Set the initial arbitration price. * @param _arbitrationPrice Amount to be paid for arbitration. */ constructor(uint _arbitrationPrice) public { arbitrationPrice = _arbitrationPrice; } /** @dev Set the arbitration price. Only callable by the owner. * @param _arbitrationPrice Amount to be paid for arbitration. */ function setArbitrationPrice(uint _arbitrationPrice) public onlyOwner { arbitrationPrice = _arbitrationPrice; } /** @dev Cost of arbitration. Accessor to arbitrationPrice. * @param _extraData Not used by this contract. * @return fee Amount to be paid. */ function arbitrationCost(bytes memory _extraData) public view returns(uint fee) { return arbitrationPrice; } /** @dev Cost of appeal. Since it is not possible, it's a high value which can never be paid. * @param _disputeID ID of the dispute to be appealed. Not used by this contract. * @param _extraData Not used by this contract. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint fee) { return NOT_PAYABLE_VALUE; } /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(). * @param _choices Amount of choices the arbitrator can make in this dispute. When ruling ruling<=choices. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes memory _extraData) public payable returns(uint disputeID) { super.createDispute(_choices, _extraData); disputeID = disputes.push(DisputeStruct({ arbitrated: Arbitrable(msg.sender), choices: _choices, fee: msg.value, ruling: 0, status: DisputeStatus.Waiting })) - 1; // Create the dispute and return its number. emit DisputeCreation(disputeID, Arbitrable(msg.sender)); } /** @dev Give a ruling. UNTRUSTED. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision". */ function _giveRuling(uint _disputeID, uint _ruling) internal { DisputeStruct storage dispute = disputes[_disputeID]; require(_ruling <= dispute.choices, "Invalid ruling."); require(dispute.status != DisputeStatus.Solved, "The dispute must not be solved already."); dispute.ruling = _ruling; dispute.status = DisputeStatus.Solved; msg.sender.send(dispute.fee); // Avoid blocking. dispute.arbitrated.rule(_disputeID,_ruling); } /** @dev Give a ruling. UNTRUSTED. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision". */ function giveRuling(uint _disputeID, uint _ruling) public onlyOwner { return _giveRuling(_disputeID, _ruling); } /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { return disputes[_disputeID].status; } /** @dev Return the ruling of a dispute. * @param _disputeID ID of the dispute to rule. * @return ruling The ruling which would or has been given. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { return disputes[_disputeID].ruling; } } /** * @title AppealableArbitrator * @dev A centralized arbitrator that can be appealed. */ contract AppealableArbitrator is CentralizedArbitrator, Arbitrable { /* Structs */ struct AppealDispute { uint rulingTime; Arbitrator arbitrator; uint appealDisputeID; } /* Storage */ uint public timeOut; mapping(uint => AppealDispute) public appealDisputes; mapping(uint => uint) public appealDisputeIDsToDisputeIDs; /* Constructor */ /** @dev Constructs the `AppealableArbitrator` contract. * @param _arbitrationPrice The amount to be paid for arbitration. * @param _arbitrator The back up arbitrator. * @param _arbitratorExtraData Not used by this contract. * @param _timeOut The time out for the appeal period. */ constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut ) public CentralizedArbitrator(_arbitrationPrice) Arbitrable(_arbitrator, _arbitratorExtraData) { timeOut = _timeOut; } /* External */ /** @dev Changes the back up arbitrator. * @param _arbitrator The new back up arbitrator. */ function changeArbitrator(Arbitrator _arbitrator) external onlyOwner { arbitrator = _arbitrator; } /** @dev Changes the time out. * @param _timeOut The new time out. */ function changeTimeOut(uint _timeOut) external onlyOwner { timeOut = _timeOut; } /* External Views */ /** @dev Gets the specified dispute's latest appeal ID. * @param _disputeID The ID of the dispute. */ function getAppealDisputeID(uint _disputeID) external view returns(uint disputeID) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) disputeID = AppealableArbitrator(address(appealDisputes[_disputeID].arbitrator)).getAppealDisputeID(appealDisputes[_disputeID].appealDisputeID); else disputeID = _disputeID; } /* Public */ /** @dev Appeals a ruling. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. */ function appeal(uint _disputeID, bytes memory _extraData) public payable requireAppealFee(_disputeID, _extraData) { super.appeal(_disputeID, _extraData); if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) appealDisputes[_disputeID].arbitrator.appeal.value(msg.value)(appealDisputes[_disputeID].appealDisputeID, _extraData); else { appealDisputes[_disputeID].arbitrator = arbitrator; appealDisputes[_disputeID].appealDisputeID = arbitrator.createDispute.value(msg.value)(disputes[_disputeID].choices, _extraData); appealDisputeIDsToDisputeIDs[appealDisputes[_disputeID].appealDisputeID] = _disputeID; } } /** @dev Gives a ruling. * @param _disputeID The ID of the dispute. * @param _ruling The ruling. */ function giveRuling(uint _disputeID, uint _ruling) public { require(disputes[_disputeID].status != DisputeStatus.Solved, "The specified dispute is already resolved."); if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) { require(Arbitrator(msg.sender) == appealDisputes[_disputeID].arbitrator, "Appealed disputes must be ruled by their back up arbitrator."); super._giveRuling(_disputeID, _ruling); } else { require(msg.sender == owner, "Not appealed disputes must be ruled by the owner."); if (disputes[_disputeID].status == DisputeStatus.Appealable) { if (now - appealDisputes[_disputeID].rulingTime > timeOut) super._giveRuling(_disputeID, disputes[_disputeID].ruling); else revert("Time out time has not passed yet."); } else { disputes[_disputeID].ruling = _ruling; disputes[_disputeID].status = DisputeStatus.Appealable; appealDisputes[_disputeID].rulingTime = now; emit AppealPossible(_disputeID, disputes[_disputeID].arbitrated); } } } /* Public Views */ /** @dev Gets the cost of appeal for the specified dispute. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. * @return The cost of the appeal. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint cost) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) cost = appealDisputes[_disputeID].arbitrator.appealCost(appealDisputes[_disputeID].appealDisputeID, _extraData); else if (disputes[_disputeID].status == DisputeStatus.Appealable) cost = arbitrator.arbitrationCost(_extraData); else cost = NOT_PAYABLE_VALUE; } /** @dev Gets the status of the specified dispute. * @param _disputeID The ID of the dispute. * @return The status. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) status = appealDisputes[_disputeID].arbitrator.disputeStatus(appealDisputes[_disputeID].appealDisputeID); else status = disputes[_disputeID].status; } /** @dev Return the ruling of a dispute. * @param _disputeID ID of the dispute to rule. * @return ruling The ruling which would or has been given. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) // Appealed. ruling = appealDisputes[_disputeID].arbitrator.currentRuling(appealDisputes[_disputeID].appealDisputeID); // Retrieve ruling from the arbitrator whom the dispute is appealed to. else ruling = disputes[_disputeID].ruling; // Not appealed, basic case. } /* Internal */ /** @dev Executes the ruling of the specified dispute. * @param _disputeID The ID of the dispute. * @param _ruling The ruling. */ function executeRuling(uint _disputeID, uint _ruling) internal { require( appealDisputes[appealDisputeIDsToDisputeIDs[_disputeID]].arbitrator != Arbitrator(address(0)), "The dispute must have been appealed." ); giveRuling(appealDisputeIDsToDisputeIDs[_disputeID], _ruling); } } /** * @title EnhancedAppealableArbitrator * @author Enrique Piqueras - <[email protected]> * @dev Implementation of `AppealableArbitrator` that supports `appealPeriod`. */ contract EnhancedAppealableArbitrator is AppealableArbitrator { /* Constructor */ /** @dev Constructs the `EnhancedAppealableArbitrator` contract. * @param _arbitrationPrice The amount to be paid for arbitration. * @param _arbitrator The back up arbitrator. * @param _arbitratorExtraData Not used by this contract. * @param _timeOut The time out for the appeal period. */ constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut ) public AppealableArbitrator(_arbitrationPrice, _arbitrator, _arbitratorExtraData, _timeOut) {} /* Public Views */ /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) (start, end) = appealDisputes[_disputeID].arbitrator.appealPeriod(appealDisputes[_disputeID].appealDisputeID); else { start = appealDisputes[_disputeID].rulingTime; require(start != 0, "The specified dispute is not appealable."); end = start + timeOut; } } } /** * @title Permission Interface * This is a permission interface for arbitrary values. The values can be cast to the required types. */ interface PermissionInterface { /** * @dev Return true if the value is allowed. * @param _value The value we want to check. * @return allowed True if the value is allowed, false otherwise. */ function isPermitted(bytes32 _value) external view returns (bool allowed); } /** * @title ArbitrableBetList * This smart contract is a viewer moderation for the bet goal contract. * This is working progress. */ contract ArbitrableBetList is IArbitrable { using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. /* Enums */ enum BetStatus { Absent, // The bet is not in the registry. Registered, // The bet is in the registry. RegistrationRequested, // The bet has a request to be added to the registry. ClearingRequested // The bet has a request to be removed from the registry. } enum Party { None, // Party per default when there is no challenger or requester. Also used for unconclusive ruling. Requester, // Party that made the request to change a bet status. Challenger // Party that challenges the request to change a bet status. } // ************************ // // * Request Life Cycle * // // ************************ // // Changes to the bet status are made via requests for either listing or removing a bet from the Bet Curated Registry. // To make or challenge a request, a party must pay a deposit. This value will be rewarded to the party that ultimately wins a dispute. If no one challenges the request, the value will be reimbursed to the requester. // Additionally to the challenge reward, in the case a party challenges a request, both sides must fully pay the amount of arbitration fees required to raise a dispute. The party that ultimately wins the case will be reimbursed. // Finally, arbitration fees can be crowdsourced. To incentivise insurers, an additional fee stake must be deposited. Contributors that fund the side that ultimately wins a dispute will be reimbursed and rewarded with the other side's fee stake proportionally to their contribution. // In summary, costs for placing or challenging a request are the following: // - A challenge reward given to the party that wins a potential dispute. // - Arbitration fees used to pay jurors. // - A fee stake that is distributed among insurers of the side that ultimately wins a dispute. /* Structs */ struct Bet { BetStatus status; // The status of the bet. Request[] requests; // List of status change requests made for the bet. } // Some arrays below have 3 elements to map with the Party enums for better readability: // - 0: is unused, matches `Party.None`. // - 1: for `Party.Requester`. // - 2: for `Party.Challenger`. struct Request { bool disputed; // True if a dispute was raised. uint disputeID; // ID of the dispute, if any. uint submissionTime; // Time when the request was made. Used to track when the challenge period ends. bool resolved; // True if the request was executed and/or any disputes raised were resolved. address[3] parties; // Address of requester and challenger, if any. Round[] rounds; // Tracks each round of a dispute. Party ruling; // The final ruling given, if any. Arbitrator arbitrator; // The arbitrator trusted to solve disputes for this request. bytes arbitratorExtraData; // The extra data for the trusted arbitrator of this request. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side on this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint[3]) contributions; // Maps contributors to their contributions for each side. } /* Storage */ // Constants uint RULING_OPTIONS = 2; // The amount of non 0 choices the arbitrator can give. // Settings address public governor; // The address that can make governance changes to the parameters of the Bet Curated Registry. Arbitrator arbitrator; bytes public arbitratorExtraData; address public selfCommitmentRegistry; // The address of the selfCommitmentRegistry contract. uint public requesterBaseDeposit; // The base deposit to make a request. uint public challengerBaseDeposit; // The base deposit to challenge a request. uint public challengePeriodDuration; // The time before a request becomes executable if not challenged. uint public metaEvidenceUpdates; // The number of times the meta evidence has been updated. Used to track the latest meta evidence ID. // The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round. // Multipliers are in basis points. uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round. uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where there isn't a winner and loser (e.g. when it's the first round or the arbitrator ruled "refused to rule"/"could not rule"). uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. // Registry data. mapping(uint => Bet) public bets; // Maps the uint bet to the bet data. mapping(address => mapping(uint => uint)) public arbitratorDisputeIDToBetID; // Maps a dispute ID to the bet with the disputed request. uint[] public betList; // List of submitted bets. /* Modifiers */ modifier onlyGovernor {require(msg.sender == governor, "The caller must be the governor."); _;} /* Events */ /** * @dev Emitted when a party submits a new bet. * @param _betID The bet. * @param _requester The address of the party that made the request. */ event BetSubmitted(uint indexed _betID, address indexed _requester); /** @dev Emitted when a party makes a request to change a bet status. * @param _betID The bet index. * @param _registrationRequest Whether the request is a registration request. False means it is a clearing request. */ event RequestSubmitted(uint indexed _betID, bool _registrationRequest); /** * @dev Emitted when a party makes a request, dispute or appeals are raised, or when a request is resolved. * @param _requester Address of the party that submitted the request. * @param _challenger Address of the party that has challenged the request, if any. * @param _betID The address. * @param _status The status of the bet. * @param _disputed Whether the bet is disputed. * @param _appealed Whether the current round was appealed. */ event BetStatusChange( address indexed _requester, address indexed _challenger, uint indexed _betID, BetStatus _status, bool _disputed, bool _appealed ); /** @dev Emitted when a reimbursements and/or contribution rewards are withdrawn. * @param _betID The bet ID from which the withdrawal was made. * @param _contributor The address that sent the contribution. * @param _request The request from which the withdrawal was made. * @param _round The round from which the reward was taken. * @param _value The value of the reward. */ event RewardWithdrawal(uint indexed _betID, address indexed _contributor, uint indexed _request, uint _round, uint _value); /* Constructor */ /** * @dev Constructs the arbitrable token curated registry. * @param _arbitrator The trusted arbitrator to resolve potential disputes. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _registrationMetaEvidence The URI of the meta evidence object for registration requests. * @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests. * @param _governor The trusted governor of this contract. * @param _requesterBaseDeposit The base deposit to make a request. * @param _challengerBaseDeposit The base deposit to challenge a request. * @param _challengePeriodDuration The time in seconds, parties have to challenge a request. * @param _sharedStakeMultiplier Multiplier of the arbitration cost that each party must pay as fee stake for a round when there isn't a winner/loser in the previous round (e.g. when it's the first round or the arbitrator refused to or did not rule). In basis points. * @param _winnerStakeMultiplier Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. * @param _loserStakeMultiplier Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. */ constructor( Arbitrator _arbitrator, bytes memory _arbitratorExtraData, string memory _registrationMetaEvidence, string memory _clearingMetaEvidence, address _governor, uint _requesterBaseDeposit, uint _challengerBaseDeposit, uint _challengePeriodDuration, uint _sharedStakeMultiplier, uint _winnerStakeMultiplier, uint _loserStakeMultiplier ) public { emit MetaEvidence(0, _registrationMetaEvidence); emit MetaEvidence(1, _clearingMetaEvidence); governor = _governor; arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; requesterBaseDeposit = _requesterBaseDeposit; challengerBaseDeposit = _challengerBaseDeposit; challengePeriodDuration = _challengePeriodDuration; sharedStakeMultiplier = _sharedStakeMultiplier; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; } /* External and Public */ // ************************ // // * Requests * // // ************************ // /** @dev Submits a request to change an address status. Accepts enough ETH to fund a potential dispute considering the current required amount and reimburses the rest. TRUSTED. * @param _betID The address. * @param _sender The address of the sender. */ function requestStatusChange(uint _betID, address payable _sender) external payable { Bet storage bet = bets[_betID]; if (bet.requests.length == 0) { // Initial bet registration. require(msg.sender == selfCommitmentRegistry); betList.push(_betID); emit BetSubmitted(_betID, _sender); } // Update bet status. if (bet.status == BetStatus.Absent) bet.status = BetStatus.RegistrationRequested; else if (bet.status == BetStatus.Registered) bet.status = BetStatus.ClearingRequested; else revert("Bet already has a pending request."); // Setup request. Request storage request = bet.requests[bet.requests.length++]; request.parties[uint(Party.Requester)] = _sender; request.submissionTime = now; request.arbitrator = arbitrator; request.arbitratorExtraData = arbitratorExtraData; Round storage round = request.rounds[request.rounds.length++]; emit RequestSubmitted(_betID, bet.status == BetStatus.RegistrationRequested); // Amount required to fully the requester: requesterBaseDeposit + arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = request.arbitrator.arbitrationCost(request.arbitratorExtraData); uint totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(requesterBaseDeposit); contribute(round, Party.Requester, _sender, msg.value, totalCost); require(round.paidFees[uint(Party.Requester)] >= totalCost, "You must fully fund your side."); round.hasPaid[uint(Party.Requester)] = true; emit BetStatusChange( request.parties[uint(Party.Requester)], address(0x0), _betID, bet.status, false, false ); } /** @dev Get the total cost */ function getTotalCost() external view returns (uint totalCost) { uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(requesterBaseDeposit); } /** @dev Challenges the latest request of a bet. Accepts enough ETH to fund a potential dispute considering the current required amount. Reimburses unused ETH. TRUSTED. * @param _betID The bet ID with the request to challenge. * @param _evidence A link to an evidence using its URI. Ignored if not provided or if not enough funds were provided to create a dispute. */ function challengeRequest(uint _betID, string calldata _evidence) external payable { Bet storage bet = bets[_betID]; require( bet.status == BetStatus.RegistrationRequested || bet.status == BetStatus.ClearingRequested, "The bet must have a pending request." ); Request storage request = bet.requests[bet.requests.length - 1]; require(now - request.submissionTime <= challengePeriodDuration, "Challenges must occur during the challenge period."); require(!request.disputed, "The request should not have already been disputed."); // Take the deposit and save the challenger's bet. request.parties[uint(Party.Challenger)] = msg.sender; Round storage round = request.rounds[request.rounds.length - 1]; uint arbitrationCost = request.arbitrator.arbitrationCost(request.arbitratorExtraData); uint totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(challengerBaseDeposit); contribute(round, Party.Challenger, msg.sender, msg.value, totalCost); require(round.paidFees[uint(Party.Challenger)] >= totalCost, "You must fully fund your side."); round.hasPaid[uint(Party.Challenger)] = true; // Raise a dispute. request.disputeID = request.arbitrator.createDispute.value(arbitrationCost)(RULING_OPTIONS, request.arbitratorExtraData); arbitratorDisputeIDToBetID[address(request.arbitrator)][request.disputeID] = _betID; request.disputed = true; request.rounds.length++; round.feeRewards = round.feeRewards.subCap(arbitrationCost); emit Dispute( request.arbitrator, request.disputeID, bet.status == BetStatus.RegistrationRequested ? 2 * metaEvidenceUpdates : 2 * metaEvidenceUpdates + 1, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))) ); emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], _betID, bet.status, true, false ); if (bytes(_evidence).length > 0) emit Evidence(request.arbitrator, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))), msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. TRUSTED. * @param _betID The bet index. * @param _side The recipient of the contribution. */ function fundAppeal(uint _betID, Party _side) external payable { // Recipient must be either the requester or challenger. require(_side == Party.Requester || _side == Party.Challenger); // solium-disable-line error-reason Bet storage bet = bets[_betID]; require( bet.status == BetStatus.RegistrationRequested || bet.status == BetStatus.ClearingRequested, "The bet must have a pending request." ); Request storage request = bet.requests[bet.requests.length - 1]; require(request.disputed, "A dispute must have been raised to fund an appeal."); (uint appealPeriodStart, uint appealPeriodEnd) = request.arbitrator.appealPeriod(request.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Contributions must be made within the appeal period." ); // Amount required to fully fund each side: arbitration cost + (arbitration cost * multiplier) Round storage round = request.rounds[request.rounds.length - 1]; Party winner = Party(request.arbitrator.currentRuling(request.disputeID)); Party loser; if (winner == Party.Requester) loser = Party.Challenger; else if (winner == Party.Challenger) loser = Party.Requester; require(!(_side==loser) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period."); uint multiplier; if (_side == winner) multiplier = winnerStakeMultiplier; else if (_side == loser) multiplier = loserStakeMultiplier; else multiplier = sharedStakeMultiplier; uint appealCost = request.arbitrator.appealCost(request.disputeID, request.arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); contribute(round, _side, msg.sender, msg.value, totalCost); if (round.paidFees[uint(_side)] >= totalCost) round.hasPaid[uint(_side)] = true; // Raise appeal if both sides are fully funded. if (round.hasPaid[uint(Party.Challenger)] && round.hasPaid[uint(Party.Requester)]) { request.arbitrator.appeal.value(appealCost)(request.disputeID, request.arbitratorExtraData); request.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], _betID, bet.status, true, true ); } } /** @dev Reimburses contributions if no disputes were raised. If a dispute was raised, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions to a request. * @param _betID The bet index submission with the request from which to withdraw. * @param _request The request from which to withdraw. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards(address payable _beneficiary, uint _betID, uint _request, uint _round) public { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; Round storage round = request.rounds[_round]; // The request must be executed and there can be no disputes pending resolution. require(request.resolved); // solium-disable-line error-reason uint reward; if (!round.hasPaid[uint(Party.Requester)] || !round.hasPaid[uint(Party.Challenger)]) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint(Party.Requester)] + round.contributions[_beneficiary][uint(Party.Challenger)]; round.contributions[_beneficiary][uint(Party.Requester)] = 0; round.contributions[_beneficiary][uint(Party.Challenger)] = 0; } else if (request.ruling == Party.None) { // No disputes were raised, or there isn't a winner and loser. Reimburse unspent fees proportionally. uint rewardRequester = round.paidFees[uint(Party.Requester)] > 0 ? (round.contributions[_beneficiary][uint(Party.Requester)] * round.feeRewards) / (round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)]) : 0; uint rewardChallenger = round.paidFees[uint(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)]) : 0; reward = rewardRequester + rewardChallenger; round.contributions[_beneficiary][uint(Party.Requester)] = 0; round.contributions[_beneficiary][uint(Party.Challenger)] = 0; } else { // Reward the winner. reward = round.paidFees[uint(request.ruling)] > 0 ? (round.contributions[_beneficiary][uint(request.ruling)] * round.feeRewards) / round.paidFees[uint(request.ruling)] : 0; round.contributions[_beneficiary][uint(request.ruling)] = 0; } emit RewardWithdrawal(_betID, _beneficiary, _request, _round, reward); _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Withdraws rewards and reimbursements of multiple rounds at once. This function is O(n) where n is the number of rounds. This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions to the request. * @param _betID The bet index. * @param _request The request from which to withdraw contributions. * @param _cursor The round from where to start withdrawing. * @param _count Rounds greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchRoundWithdraw(address payable _beneficiary, uint _betID, uint _request, uint _cursor, uint _count) public { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; for (uint i = _cursor; i<request.rounds.length && (_count==0 || i<_count); i++) withdrawFeesAndRewards(_beneficiary, _betID, _request, i); } /** @dev Withdraws rewards and reimbursements of multiple requests at once. This function is O(n*m) where n is the number of requests and m is the number of rounds. This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions to the request. * @param _betID The bet index. * @param _cursor The request from which to start withdrawing. * @param _count Requests greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of request, iterates until the last request. * @param _roundCursor The round of each request from where to start withdrawing. * @param _roundCount Rounds greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of rounds a request has, iteration for that request will stop at the last round. */ function batchRequestWithdraw( address payable _beneficiary, uint _betID, uint _cursor, uint _count, uint _roundCursor, uint _roundCount ) external { Bet storage bet = bets[_betID]; for (uint i = _cursor; i<bet.requests.length && (_count==0 || i<_count); i++) batchRoundWithdraw(_beneficiary, _betID, i, _roundCursor, _roundCount); } /** @dev Executes a request if the challenge period passed and no one challenged the request. * @param _betID The bet index with the request to execute. */ function executeRequest(uint _betID) external { Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; require( now - request.submissionTime > challengePeriodDuration, "Time to challenge the request must have passed." ); require(!request.disputed, "The request should not be disputed."); if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Registered; else if (bet.status == BetStatus.ClearingRequested) bet.status = BetStatus.Absent; else revert("There must be a request."); request.resolved = true; address payable party = address(uint160(request.parties[uint(Party.Requester)])); withdrawFeesAndRewards(party, _betID, bet.requests.length - 1, 0); // Automatically withdraw for the requester. emit BetStatusChange( request.parties[uint(Party.Requester)], address(0x0), _betID, bet.status, false, false ); } /** @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED. * Overrides parent function to account for the situation where the winner loses a case due to paying less appeal fees than expected. * @param _disputeID ID of the dispute in the arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { Party resultRuling = Party(_ruling); uint _betID = arbitratorDisputeIDToBetID[msg.sender][_disputeID]; Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; Round storage round = request.rounds[request.rounds.length - 1]; require(_ruling <= RULING_OPTIONS); // solium-disable-line error-reason require(address(request.arbitrator) == msg.sender); // solium-disable-line error-reason require(!request.resolved); // solium-disable-line error-reason // The ruling is inverted if the loser paid its fees. if (round.hasPaid[uint(Party.Requester)] == true) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created. resultRuling = Party.Requester; else if (round.hasPaid[uint(Party.Challenger)] == true) resultRuling = Party.Challenger; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(_disputeID, uint(resultRuling)); } /** @dev Submit a reference to evidence. EVENT. * @param _betID The bet index. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _betID, string calldata _evidence) external { Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; require(!request.resolved, "The dispute must not already be resolved."); emit Evidence(request.arbitrator, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))), msg.sender, _evidence); } // ************************ // // * Governance * // // ************************ // /** @dev Change the duration of the challenge period. * @param _challengePeriodDuration The new duration of the challenge period. */ function changeTimeToChallenge(uint _challengePeriodDuration) external onlyGovernor { challengePeriodDuration = _challengePeriodDuration; } /** @dev Change the base amount required as a deposit to make a request. * @param _requesterBaseDeposit The new base amount of wei required to make a request. */ function changeRequesterBaseDeposit(uint _requesterBaseDeposit) external onlyGovernor { requesterBaseDeposit = _requesterBaseDeposit; } /** @dev Change the base amount required as a deposit to challenge a request. * @param _challengerBaseDeposit The new base amount of wei required to challenge a request. */ function changeChallengerBaseDeposit(uint _challengerBaseDeposit) external onlyGovernor { challengerBaseDeposit = _challengerBaseDeposit; } /** @dev Change the governor of the token curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the address of the goal bet registry contract. * @param _selfCommitmentRegistry The address of the new goal bet registry contract. */ function changeSelfCommitmentRegistry(address _selfCommitmentRegistry) external onlyGovernor { selfCommitmentRegistry = _selfCommitmentRegistry; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by parties when there isn't a winner or loser. * @param _sharedStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeSharedStakeMultiplier(uint _sharedStakeMultiplier) external onlyGovernor { sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by the winner of the previous round. * @param _winnerStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeWinnerStakeMultiplier(uint _winnerStakeMultiplier) external onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by the party that lost the previous round. * @param _loserStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeLoserStakeMultiplier(uint _loserStakeMultiplier) external onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; } /** @dev Change the arbitrator to be used for disputes that may be raised in the next requests. The arbitrator is trusted to support appeal periods and not reenter. * @param _arbitrator The new trusted arbitrator to be used in the next requests. * @param _arbitratorExtraData The extra data used by the new arbitrator. */ function changeArbitrator(Arbitrator _arbitrator, bytes calldata _arbitratorExtraData) external onlyGovernor { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Update the meta evidence used for disputes. * @param _registrationMetaEvidence The meta evidence to be used for future registration request disputes. * @param _clearingMetaEvidence The meta evidence to be used for future clearing request disputes. */ function changeMetaEvidence(string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence) external onlyGovernor { metaEvidenceUpdates++; emit MetaEvidence(2 * metaEvidenceUpdates, _registrationMetaEvidence); emit MetaEvidence(2 * metaEvidenceUpdates + 1, _clearingMetaEvidence); } /* Internal */ /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute(Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired) internal { // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @dev Execute the ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal { uint betID = arbitratorDisputeIDToBetID[msg.sender][_disputeID]; Bet storage bet = bets[betID]; Request storage request = bet.requests[bet.requests.length - 1]; Party winner = Party(_ruling); // Update bet state if (winner == Party.Requester) { // Execute Request if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Registered; else bet.status = BetStatus.Absent; } else { // Revert to previous state. if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Absent; else if (bet.status == BetStatus.ClearingRequested) bet.status = BetStatus.Registered; } request.resolved = true; request.ruling = Party(_ruling); // Automatically withdraw. if (winner == Party.None) { address payable requester = address(uint160(request.parties[uint(Party.Requester)])); address payable challenger = address(uint160(request.parties[uint(Party.Challenger)])); withdrawFeesAndRewards(requester, betID, bet.requests.length-1, 0); withdrawFeesAndRewards(challenger, betID, bet.requests.length-1, 0); } else { address payable winnerAddr = address(uint160(request.parties[uint(winner)])); withdrawFeesAndRewards(winnerAddr, betID, bet.requests.length-1, 0); } emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], betID, bet.status, request.disputed, false ); } /* Views */ /** @dev Return true if the bet is on the list. * @param _betID The bet index. * @return allowed True if the address is allowed, false otherwise. */ function isPermitted(uint _betID) external view returns (bool allowed) { Bet storage bet = bets[_betID]; return bet.status == BetStatus.Registered || bet.status == BetStatus.ClearingRequested; } /* Interface Views */ /** @dev Return the sum of withdrawable wei of a request an account is entitled to. This function is O(n), where n is the number of rounds of the request. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _betID The bet index to query. * @param _beneficiary The contributor for which to query. * @param _request The request from which to query for. * @return The total amount of wei available to withdraw. */ function amountWithdrawable(uint _betID, address _beneficiary, uint _request) external view returns (uint total){ Request storage request = bets[_betID].requests[_request]; if (!request.resolved) return total; for (uint i = 0; i < request.rounds.length; i++) { Round storage round = request.rounds[i]; if (!request.disputed || request.ruling == Party.None) { uint rewardRequester = round.paidFees[uint(Party.Requester)] > 0 ? (round.contributions[_beneficiary][uint(Party.Requester)] * round.feeRewards) / (round.paidFees[uint(Party.Requester)] + round.paidFees[uint(Party.Challenger)]) : 0; uint rewardChallenger = round.paidFees[uint(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint(Party.Requester)] + round.paidFees[uint(Party.Challenger)]) : 0; total += rewardRequester + rewardChallenger; } else { total += round.paidFees[uint(request.ruling)] > 0 ? (round.contributions[_beneficiary][uint(request.ruling)] * round.feeRewards) / round.paidFees[uint(request.ruling)] : 0; } } return total; } /** @dev Return the numbers of bets that were submitted. Includes bets that never made it to the list or were later removed. * @return count The numbers of bets in the list. */ function betCount() external view returns (uint count) { return betList.length; } /** @dev Gets the contributions made by a party for a given round of a request. * @param _betID The bet index. * @param _request The position of the request. * @param _round The position of the round. * @param _contributor The address of the contributor. * @return The contributions. */ function getContributions( uint _betID, uint _request, uint _round, address _contributor ) external view returns(uint[3] memory contributions) { Request storage request = bets[_betID].requests[_request]; Round storage round = request.rounds[_round]; contributions = round.contributions[_contributor]; } /** @dev Returns bet information. Includes length of requests array. * @param _betID The queried bet index. * @return The bet information. */ function getBetInfo(uint _betID) external view returns ( BetStatus status, uint numberOfRequests ) { Bet storage bet = bets[_betID]; return ( bet.status, bet.requests.length ); } /** @dev Gets information on a request made for a bet. * @param _betID The queried bet index. * @param _request The request to be queried. * @return The request information. */ function getRequestInfo(uint _betID, uint _request) external view returns ( bool disputed, uint disputeID, uint submissionTime, bool resolved, address[3] memory parties, uint numberOfRounds, Party ruling, Arbitrator arbitratorRequest, bytes memory arbitratorExtraData ) { Request storage request = bets[_betID].requests[_request]; return ( request.disputed, request.disputeID, request.submissionTime, request.resolved, request.parties, request.rounds.length, request.ruling, request.arbitrator, request.arbitratorExtraData ); } /** @dev Gets the information on a round of a request. * @param _betID The queried bet index. * @param _request The request to be queried. * @param _round The round to be queried. * @return The round information. */ function getRoundInfo(uint _betID, uint _request, uint _round) external view returns ( bool appealed, uint[3] memory paidFees, bool[3] memory hasPaid, uint feeRewards ) { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; Round storage round = request.rounds[_round]; return ( _round != (request.rounds.length-1), round.paidFees, round.hasPaid, round.feeRewards ); } } contract SelfCommitment is IArbitrable { using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. // **************************** // // * Contract variables * // // **************************** // struct Bet { string description; // alias metaevidence uint[3] period; // endBetPeriod, startClaimPeriod, endClaimPeriod uint[2] ratio; // For irrational numbers we assume that the loss of wei is negligible address[3] parties; uint[2] amount; // betterAmount (max), takerTotalAmount mapping(address => uint) amountTaker; bool isPrivate; mapping(address => bool) allowAddress; Arbitrator arbitrator; bytes arbitratorExtraData; uint[3] stakeMultiplier; Status status; // Status of the claim relative to a dispute. uint disputeID; // If dispute exists, the ID of the dispute. Round[] rounds; // Tracks each round of a dispute. Party ruling; // The final ruling given, if any. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side on this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint[3]) contributions; // Maps contributors to their contributions for each side. } Bet[] public bets; // Amount of choices to solve the dispute if needed. uint8 constant AMOUNT_OF_CHOICES = 2; // Enum relative to different periods in the case of a negotiation or dispute. enum Status {NoDispute, WaitingAsker, WaitingTaker, DisputeCreated, Resolved} // The different parties of the dispute. enum Party {None, Asker, Taker} // The different ruling for the dispute resolution. enum RulingOptions {NoRuling, AskerWins, TakerWins} // One-to-one relationship between the dispute and the bet. mapping(address => mapping(uint => uint)) public arbitratorDisputeIDtoBetID; // Settings address public governor; // The address that can make governance changes to the parameters. address public betArbitrableList; uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. // **************************** // // * Modifier * // // **************************** // modifier onlyGovernor {require(msg.sender == address(governor), "The caller must be the governor."); _;} // **************************** // // * Events * // // **************************** // /** @dev Indicate that a party has to pay a fee or would otherwise be considered as losing. * @param _transactionID The index of the transaction. * @param _party The party who has to pay. */ event HasToPayFee(uint indexed _transactionID, Party _party); /** @dev To be emitted when a party get the rewards or the deposit. * @param _id The index of the bet. * @param _party The party that paid. * @param _amount The amount paid. */ event Reward(uint indexed _id, Party _party, uint _amount); /** @dev Emitted when a reimbursements and/or contribution rewards are withdrawn. * @param _id The ID of the bet. * @param _contributor The address that sent the contribution. * @param _round The round from which the reward was taken. * @param _value The value of the reward. */ event RewardWithdrawal(uint indexed _id, address indexed _contributor, uint _round, uint _value); /* Constructor */ /** * @dev Constructs the arbitrable token curated registry. * @param _governor The trusted governor of this contract. */ constructor( address _governor ) public { governor = _governor; } // **************************** // // * Contract functions * // // * Modifying the state * // // **************************** // /** @dev To add a new bet. UNTRUSTED. * @param _description The description of the bet. * @param _period The different periods of the bet. * @param _ratio The ratio of the bet. * @param _allowAddress Addresses who are allowed to bet. Empty for all addresses. * @param _arbitrator The arbitrator of the bet. * @param _arbitratorExtraData The configuration for the arbitration. * @param _stakeMultiplier The multipler of the deposit for the different parties. */ function ask( string calldata _description, uint[3] calldata _period, uint[2] calldata _ratio, address[] calldata _allowAddress, Arbitrator _arbitrator, bytes calldata _arbitratorExtraData, uint[3] calldata _stakeMultiplier ) external payable { ArbitrableBetList betArbitrableListInstance = ArbitrableBetList(betArbitrableList); uint totalCost = betArbitrableListInstance.getTotalCost(); require(msg.value > totalCost); require(msg.value - totalCost >= 10000); require(_ratio[0] > 1); require(_ratio[0] > _ratio[1]); require(_period[0] > now); uint amountXratio1 = msg.value * _ratio[0]; // _ratio0 > (_ratio0/_ratio1) require(amountXratio1/msg.value == _ratio[0]); // To prevent multiply overflow. betArbitrableListInstance.requestStatusChange.value(totalCost)(bets.length, msg.sender); Bet storage bet = bets[bets.length++]; bet.parties[1] = msg.sender; bet.description = _description; bet.period = _period; bet.ratio = _ratio; bet.amount = [msg.value - totalCost, 0]; if (_allowAddress.length > 0) { for(uint i; i < _allowAddress.length; i++) bet.allowAddress[_allowAddress[i]] = true; bet.isPrivate = true; } bet.arbitrator = _arbitrator; bet.arbitratorExtraData = _arbitratorExtraData; bet.stakeMultiplier = _stakeMultiplier; } /** @dev To accept a bet. UNTRUSTED. * @param _id The id of the bet. */ function take( uint _id ) external payable { require(msg.value > 0); Bet storage bet = bets[_id]; require(now < bet.period[0], "Should bet before the end period bet."); require(bet.amount[0] > bet.amount[1]); if (bet.isPrivate) require(bet.allowAddress[msg.sender]); address payable taker = msg.sender; // r = bet.ratio[0] / bet.ratio[1] // maxAmountToBet = x / (r-1) - y // maxAmountToBet = x*x / (rx-x) - y uint maxAmountToBet = bet.amount[0]*bet.amount[0] / (bet.ratio[0]*bet.amount[0]/bet.ratio[1] - bet.amount[0]) - bet.amount[1]; uint amountBet = msg.value <= maxAmountToBet ? msg.value : maxAmountToBet; bet.amount[1] += amountBet; bet.amountTaker[taker] = amountBet; if (msg.value > maxAmountToBet) taker.transfer(msg.value - maxAmountToBet); } /** @dev Withdraw the bet if no one took it. TRUSTED. * @param _id The id of the bet. */ function withdraw( uint _id ) external { Bet storage bet = bets[_id]; require(now > bet.period[0], "Should end period bet finished."); if (bet.amount[1] == 0) executeRuling(_id, uint(Party.Asker)); else { uint maxAmountToTake = bet.amount[1] * bet.ratio[0] / bet.ratio[1]; uint amountToAsk = maxAmountToTake - bet.amount[1]; address payable asker = address(uint160(bet.parties[1])); require(bet.amount[0] > amountToAsk); asker.send(bet.amount[0] - amountToAsk); bet.amount[0] = amountToAsk; } } /* Section of Claims or Dispute Resolution */ /** @dev Pay the arbitration fee to claim the bet. To be called by the asker. UNTRUSTED. * Note that the arbitrator can have createDispute throw, * which will make this function throw and therefore lead to a party being timed-out. * This is not a vulnerability as the arbitrator can rule in favor of one party anyway. * @param _id The index of the bet. */ function claimAsker(uint _id) public payable { Bet storage bet = bets[_id]; require( bet.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); require(bet.parties[1] == msg.sender, "The caller must be the creator of the bet."); require(now > bet.period[1], "Should claim after the claim period start."); require(now < bet.period[2], "Should claim before the claim period end."); // Amount required to claim: arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); uint claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); // The asker must cover the claim cost. require(msg.value >= claimCost); if(bet.rounds.length == 0) bet.rounds.length++; Round storage round = bet.rounds[0]; round.hasPaid[uint(Party.Asker)] = true; contribute(round, Party.Asker, msg.sender, msg.value, claimCost); // The taker still has to pay. This can also happen if he has paid, // but arbitrationCost has increased. if (round.paidFees[uint(Party.Taker)] <= claimCost) { bet.status = Status.WaitingTaker; emit HasToPayFee(_id, Party.Taker); } else { // The taker has also paid the fee. We create the dispute raiseDispute(_id, arbitrationCost); } } /** @dev Pay the arbitration fee to claim a bet. To be called by the taker. UNTRUSTED. * @param _id The index of the claim. */ function claimTaker(uint _id) public payable { Bet storage bet = bets[_id]; require( bet.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); // NOTE: We assume that for this smart contract version, // this smart contract is vulnerable to a griefing attack. // We expect a very low ratio of griefing attack // in the majority of cases. require( bet.amountTaker[msg.sender] > 0, "The caller must be the one of the taker." ); require(now > bet.period[1], "Should claim after the claim period start."); require(now < bet.period[2], "Should claim before the claim period end."); bet.parties[2] = msg.sender; // Amount required to claim: arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); uint claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); // The taker must cover the claim cost. require(msg.value >= claimCost); if(bet.rounds.length == 0) bet.rounds.length++; Round storage round = bet.rounds[0]; round.hasPaid[uint(Party.Taker)] = true; contribute(round, Party.Taker, msg.sender, msg.value, claimCost); // The taker still has to pay. This can also happen if he has paid, // but arbitrationCost has increased. if (round.paidFees[uint(Party.Taker)] <= claimCost) { bet.status = Status.WaitingAsker; emit HasToPayFee(_id, Party.Taker); } else { // The taker has also paid the fee. We create the dispute. raiseDispute(_id, arbitrationCost); } } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute( Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired ) internal { // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Reward asker of the bet if the taker fails to pay the fee. * NOTE: The taker unspent fee are sent to the asker. * @param _id The index of the bet. */ function timeOutByAsker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingTaker, "The transaction of the bet must waiting on the taker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.AskerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); } /** @dev Pay taker if the asker fails to pay the fee. * NOTE: The asker unspent fee are sent to the taker. * @param _id The index of the claim. */ function timeOutByTaker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingAsker, "The transaction of the bet must waiting on the asker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.TakerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); } /** @dev Create a dispute. UNTRUSTED. * @param _id The index of the bet. * @param _arbitrationCost Amount to pay the arbitrator. */ function raiseDispute(uint _id, uint _arbitrationCost) internal { Bet storage bet = bets[_id]; bet.status = Status.DisputeCreated; uint disputeID = bet.arbitrator.createDispute.value(_arbitrationCost)(AMOUNT_OF_CHOICES, bet.arbitratorExtraData); arbitratorDisputeIDtoBetID[address(bet.arbitrator)][disputeID] = _id; bet.disputeID = disputeID; emit Dispute(bet.arbitrator, bet.disputeID, _id, _id); } /** @dev Submit a reference to evidence. EVENT. * @param _id The index of the claim. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _id, string memory _evidence) public { Bet storage bet = bets[_id]; require( msg.sender == bet.parties[1] || bet.amountTaker[msg.sender] > 0, "The caller must be the asker or a taker." ); require( bet.status >= Status.DisputeCreated, "The dispute has not been created yet." ); emit Evidence(bet.arbitrator, _id, msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. TRUSTED. * @param _id The ID of the bet with the request to fund. * @param _side The recipient of the contribution. */ function fundAppeal(uint _id, Party _side) external payable { // Recipient must be either the requester or challenger. require(_side == Party.Asker || _side == Party.Taker); // solium-disable-line error-reason Bet storage bet = bets[_id]; require( bet.status >= Status.DisputeCreated, "A dispute must have been raised to fund an appeal." ); (uint appealPeriodStart, uint appealPeriodEnd) = bet.arbitrator.appealPeriod(bet.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Contributions must be made within the appeal period." ); Round storage round = bet.rounds[bet.rounds.length - 1]; Party winner = Party(bet.arbitrator.currentRuling(bet.disputeID)); Party loser; if (winner == Party.Asker) loser = Party.Taker; else if (winner == Party.Taker) loser = Party.Asker; require(!(_side==loser) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period."); uint multiplier; if (_side == winner) multiplier = bet.stakeMultiplier[1]; else if (_side == loser) multiplier = bet.stakeMultiplier[2]; else multiplier = bet.stakeMultiplier[0]; uint appealCost = bet.arbitrator.appealCost(bet.disputeID, bet.arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); contribute(round, _side, msg.sender, msg.value, totalCost); if (round.paidFees[uint(_side)] >= totalCost) round.hasPaid[uint(_side)] = true; // Raise appeal if both sides are fully funded. if (round.hasPaid[uint(Party.Taker)] && round.hasPaid[uint(Party.Asker)]) { bet.arbitrator.appeal.value(appealCost)(bet.disputeID, bet.arbitratorExtraData); bet.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); } } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external { Party resultRuling = Party(_ruling); uint id = arbitratorDisputeIDtoBetID[msg.sender][_disputeID]; Bet storage bet = bets[id]; require(_ruling <= AMOUNT_OF_CHOICES); // solium-disable-line error-reason require(address(bet.arbitrator) == msg.sender); // solium-disable-line error-reason require(bet.status != Status.Resolved); // solium-disable-line error-reason Round storage round = bet.rounds[bet.rounds.length - 1]; // The ruling is inverted if the loser paid its fees. // If one side paid its fees, the ruling is in its favor. // Note that if the other side had also paid, an appeal would have been created. if (round.hasPaid[uint(Party.Asker)] == true) resultRuling = Party.Asker; else if (round.hasPaid[uint(Party.Taker)] == true) resultRuling = Party.Taker; bet.status = Status.Resolved; bet.ruling = resultRuling; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(id, uint(resultRuling)); } /** @dev Reimburses contributions if no disputes were raised. * If a dispute was raised, sends the fee stake and the reward for the winner. * @param _beneficiary The address that made contributions to a request. * @param _id The ID of the bet. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards( address payable _beneficiary, uint _id, uint _round ) public { Bet storage bet = bets[_id]; Round storage round = bet.rounds[_round]; // The request must be resolved. require(bet.status == Status.Resolved); // solium-disable-line error-reason uint reward; if (!round.hasPaid[uint(Party.Asker)] || !round.hasPaid[uint(Party.Taker)]) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint(Party.Asker)] + round.contributions[_beneficiary][uint(Party.Taker)]; round.contributions[_beneficiary][uint(Party.Asker)] = 0; round.contributions[_beneficiary][uint(Party.Taker)] = 0; if(bet.amountTaker[_beneficiary] > 0 && bet.ruling != Party.Asker) { reward += bet.amountTaker[_beneficiary] * bet.ratio[0] / bet.ratio[1]; bet.amountTaker[_beneficiary] = 0; } } else if (bet.ruling == Party.None) { // No disputes were raised, or there isn't a winner and loser. Reimburse unspent fees proportionally. uint rewardAsker = round.paidFees[uint(Party.Asker)] > 0 ? (round.contributions[_beneficiary][uint(Party.Asker)] * round.feeRewards) / (round.paidFees[uint(Party.Taker)] + round.paidFees[uint(Party.Asker)]) : 0; uint rewardTaker = round.paidFees[uint(Party.Taker)] > 0 ? (round.contributions[_beneficiary][uint(Party.Taker)] * round.feeRewards) / (round.paidFees[uint(Party.Taker)] + round.paidFees[uint(Party.Asker)]) : 0; reward = rewardAsker + rewardTaker; round.contributions[_beneficiary][uint(Party.Asker)] = 0; round.contributions[_beneficiary][uint(Party.Taker)] = 0; // Reimburse the fund bet. if(bet.amountTaker[_beneficiary] > 0) { reward += bet.amountTaker[_beneficiary]; bet.amountTaker[_beneficiary] = 0; } } else { // Reward the winner. reward = round.paidFees[uint(bet.ruling)] > 0 ? (round.contributions[_beneficiary][uint(bet.ruling)] * round.feeRewards) / round.paidFees[uint(bet.ruling)] : 0; round.contributions[_beneficiary][uint(bet.ruling)] = 0; if(bet.amountTaker[_beneficiary] > 0 && bet.ruling != Party.Asker) { reward += bet.amountTaker[_beneficiary] * bet.ratio[0] / bet.ratio[1]; bet.amountTaker[_beneficiary] = 0; } } emit RewardWithdrawal(_id, _beneficiary, _round, reward); _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Execute a ruling of a dispute. It reimburses the fee to the winning party. * @param _id The index of the bet. * @param _ruling Ruling given by the arbitrator. 1 : Reimburse the owner of the item. 2 : Pay the finder. */ function executeRuling(uint _id, uint _ruling) internal { require(_ruling <= AMOUNT_OF_CHOICES, "Invalid ruling."); Bet storage bet = bets[_id]; bet.status = Status.Resolved; address payable asker = address(uint160(bet.parties[1])); address payable taker = address(uint160(bet.parties[2])); if (_ruling == uint(Party.None)) { if(bet.amount[0] > 0) { asker.send(bet.amount[0]); bet.amount[0] = 0; } if (bet.rounds.length != 0) { withdrawFeesAndRewards(asker, _id, 0); withdrawFeesAndRewards(taker, _id, 0); } } else if (_ruling == uint(Party.Asker)) { require(bet.amount[0] > 0); asker.send(bet.amount[0] + bet.amount[1]); bet.amount[0] = 0; bet.amount[1] = 0; if (bet.rounds.length != 0) withdrawFeesAndRewards(asker, _id, 0); } else { if (bet.rounds.length != 0) withdrawFeesAndRewards(taker, _id, 0); } } /* Governance */ /** @dev Change the governor of the token curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the address of the goal bet registry contract. * @param _betArbitrableList The address of the new goal bet registry contract. */ function changeArbitrationBetList(address _betArbitrableList) external onlyGovernor { betArbitrableList = _betArbitrableList; } // **************************** // // * View functions * // // **************************** // /** @dev Get the claim cost * @param _id The index of the claim. */ function getClaimCost(uint _id) external view returns (uint claimCost) { Bet storage bet = bets[_id]; uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); } function getMaxAmountToBet( uint _id ) external view returns (uint maxAmountToBet) { Bet storage bet = bets[_id]; maxAmountToBet = bet.amount[0]*bet.amount[0] / (bet.ratio[0]*bet.amount[0] / bet.ratio[1] - bet.amount[0]) - bet.amount[1]; } /** @dev Return the values of the bets the query finds. This function is O(n), where n is the number of bets. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _cursor The bet index from which to start iterating. To start from either the oldest or newest item. * @param _count The number of bets to return. * @param _filter The filter to use. Each element of the array in sequence means: * - Include absent bets in result. * - Include registered bets in result. * - Include bets with registration requests that are not disputed in result. * - Include bets with clearing requests that are not disputed in result. * - Include disputed bets with registration requests in result. * - Include disputed bets with clearing requests in result. * - Include bets submitted by the caller. * - Include bets challenged by the caller. * - Include bets created. * - Include bets taken. * @return The values of the bets found and whether there are more bets for the current filter and sort. */ function queryBets(uint _cursor, uint _count, bool[10] calldata _filter) external view returns (uint[] memory values, bool hasMore) { values = new uint[](_count); uint index = 0; for ( uint i = _cursor == 0 ? bets.length - 1 : bets.length - 1 - _cursor; i < bets.length; i++ ) { Bet storage bet = bets[i]; ArbitrableBetList betArbitrableListInstance = ArbitrableBetList(betArbitrableList); (ArbitrableBetList.BetStatus arbitrableBetlistStatus, uint numberOfRequests) = betArbitrableListInstance.getBetInfo(i); (bool disputed, , , , address[3] memory parties, , , , ) = betArbitrableListInstance.getRequestInfo(i, numberOfRequests - 1); if ( /* solium-disable operator-whitespace */ (_filter[0] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.Absent) || (_filter[1] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.Registered) || (_filter[2] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.RegistrationRequested && !disputed) || (_filter[3] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.ClearingRequested && !disputed) || (_filter[4] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.RegistrationRequested && disputed) || (_filter[5] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.ClearingRequested && disputed) || (_filter[6] && parties[1] == msg.sender) || // My Submissions. (_filter[7] && parties[2] == msg.sender) || // My Challenges. (_filter[8] && bet.parties[1] == msg.sender) || // My bets. (_filter[9] && bet.parties[2] == msg.sender) // My taken bets. /* solium-enable operator-whitespace */ ) { if (index < _count) { values[index] = i; index++; } else { hasMore = true; break; } } } } }
Maps the uint bet to the bet data.
mapping(uint => Bet) public bets;
12,936,846
[ 1, 8903, 326, 2254, 2701, 358, 326, 2701, 501, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 11890, 516, 605, 278, 13, 1071, 324, 2413, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /* solhint-disable var-name-mixedcase */ pragma solidity ^0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./swap/ISwap.sol"; import "./SignataIdentity.sol"; /** * @title Veriswap * @notice Forked from AirSwap */ contract Veriswap is ISwap, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; bytes32 public constant DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "uint256 chainId,", "address verifyingContract", ")" ) ); bytes32 public constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "address signerWallet,", "address signerToken,", "uint256 signerAmount,", "uint256 protocolFee,", "address senderWallet,", "address senderToken,", "uint256 senderAmount", ")" ) ); bytes32 public constant DOMAIN_NAME = keccak256("VERISWAP"); bytes32 public constant DOMAIN_VERSION = keccak256("1"); uint256 public immutable DOMAIN_CHAIN_ID; bytes32 public immutable DOMAIN_SEPARATOR; SignataIdentity private signataIdentity; uint256 internal constant MAX_PERCENTAGE = 100; uint256 internal constant MAX_SCALE = 77; uint256 internal constant MAX_ERROR_COUNT = 6; uint256 public constant FEE_DIVISOR = 10000; /** * @notice Double mapping of signers to nonce groups to nonce states * @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key * @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used */ mapping(address => mapping(uint256 => uint256)) internal _nonceGroups; mapping(address => address) public override authorized; uint256 public protocolFee; uint256 public protocolFeeLight; address public protocolFeeWallet; uint256 public rebateScale; uint256 public rebateMax; address public stakingToken; constructor( uint256 _protocolFee, uint256 _protocolFeeLight, address _protocolFeeWallet, uint256 _rebateScale, uint256 _rebateMax, address _stakingToken, address _signataIdentity ) { require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE"); require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH"); require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); require(_stakingToken != address(0), "INVALID_STAKING_TOKEN"); uint256 currentChainId = getChainId(); DOMAIN_CHAIN_ID = currentChainId; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, DOMAIN_NAME, DOMAIN_VERSION, currentChainId, this ) ); protocolFee = _protocolFee; protocolFeeLight = _protocolFeeLight; protocolFeeWallet = _protocolFeeWallet; rebateScale = _rebateScale; rebateMax = _rebateMax; stakingToken = _stakingToken; signataIdentity = SignataIdentity(_signataIdentity); } /** * @notice Atomic ERC20 Swap * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param enforceIdentity bool Require the maker to have a registered Signata Identity * @param checkRisk bool Require the maker to check the Chainlink Risk Oracle * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function swap( address recipient, uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, bool enforceIdentity, bool checkRisk, uint8 v, bytes32 r, bytes32 s ) external override { // Ensure the order is valid _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderAmount, enforceIdentity, checkRisk, v, r, s ); // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom(signerWallet, recipient, signerAmount); // Calculate and transfer protocol fee and any rebate _transferProtocolFee(signerToken, signerWallet, signerAmount); // Emit a Swap event emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFee, msg.sender, senderToken, senderAmount ); } /** * @notice Swap Atomic ERC20 Swap (Low Gas Usage) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param enforceIdentity bool Require the maker to have a registered Signata Identity * @param checkRisk bool Require the maker to check the Chainlink Risk Oracle * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function light( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, bool enforceIdentity, bool checkRisk, uint8 v, bytes32 r, bytes32 s ) external override { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); // Ensure the expiry is not passed require(expiry > block.timestamp, "EXPIRY_PASSED"); // Recover the signatory from the hash and signature address signatory = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( ORDER_TYPEHASH, nonce, expiry, signerWallet, signerToken, signerAmount, protocolFeeLight, msg.sender, senderToken, senderAmount ) ) ) ), v, r, s ); // Ensure the signatory is not null require(signatory != address(0), "SIGNATURE_INVALID"); // Ensure the nonce is not yet used and if not mark it used require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED"); // Ensure the signatory is authorized by the signer wallet if (signerWallet != signatory) { require(authorized[signerWallet] == signatory, "UNAUTHORIZED"); } if (enforceIdentity) { signataIdentity.getDelegate(msg.sender); require( !signataIdentity.isLocked(msg.sender), "Veriswap: The sender's identity is locked." ); } if (checkRisk) { // TODO: drop in the chainlink integration here } // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom( signerWallet, msg.sender, signerAmount ); // Transfer fee from signer to feeWallet IERC20(signerToken).safeTransferFrom( signerWallet, protocolFeeWallet, signerAmount.mul(protocolFeeLight).div(FEE_DIVISOR) ); // Emit a Swap event emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFeeLight, msg.sender, senderToken, senderAmount ); } /** * @notice Sender Buys an NFT (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerID uint256 Token ID transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param enforceIdentity bool Require the maker to have a registered Signata Identity * @param checkRisk bool Require the maker to check the Chainlink Risk Oracle * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function buyNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerID, address senderToken, uint256 senderAmount, bool enforceIdentity, bool checkRisk, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerID, senderToken, senderAmount, enforceIdentity, checkRisk, v, r, s ); // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID); // Calculate and transfer protocol fee and rebate _transferProtocolFee(senderToken, msg.sender, senderAmount); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerID, protocolFee, msg.sender, senderToken, senderAmount ); } /** * @notice Sender Sells an NFT (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC721 token transferred from the sender * @param senderID uint256 Token ID transferred from the sender * @param enforceIdentity bool Require the maker to have a registered Signata Identity * @param checkRisk bool Require the maker to check the Chainlink Risk Oracle * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function sellNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderID, bool enforceIdentity, bool checkRisk, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderID, enforceIdentity, checkRisk, v, r, s ); // Transfer token from sender to signer IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom( signerWallet, msg.sender, signerAmount ); // Calculate and transfer protocol fee and rebate _transferProtocolFee(signerToken, signerWallet, signerAmount); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFee, msg.sender, senderToken, senderID ); } /** * @notice Signer and sender swap NFTs (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerID uint256 Token ID transferred from the signer * @param senderToken address ERC721 token transferred from the sender * @param senderID uint256 Token ID transferred from the sender * @param enforceIdentity bool Require the maker to have a registered Signata Identity * @param checkRisk bool Require the maker to check the Chainlink Risk Oracle * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function swapNFTs( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerID, address senderToken, uint256 senderID, bool enforceIdentity, bool checkRisk, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerID, senderToken, senderID, enforceIdentity, checkRisk, v, r, s ); // Transfer token from sender to signer IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID); // Transfer token from signer to sender IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerID, 0, msg.sender, senderToken, senderID ); } /** * @notice Set the fee * @param _protocolFee uint256 Value of the fee in basis points */ function setProtocolFee(uint256 _protocolFee) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); protocolFee = _protocolFee; emit SetProtocolFee(_protocolFee); } /** * @notice Set the light fee * @param _protocolFeeLight uint256 Value of the fee in basis points */ function setProtocolFeeLight(uint256 _protocolFeeLight) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE_LIGHT"); protocolFeeLight = _protocolFeeLight; emit SetProtocolFeeLight(_protocolFeeLight); } /** * @notice Set the fee wallet * @param _protocolFeeWallet address Wallet to transfer fee to */ function setProtocolFeeWallet(address _protocolFeeWallet) external onlyOwner { // Ensure the new fee wallet is not null require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); protocolFeeWallet = _protocolFeeWallet; emit SetProtocolFeeWallet(_protocolFeeWallet); } /** * @notice Set scale * @dev Only owner * @param _rebateScale uint256 */ function setRebateScale(uint256 _rebateScale) external onlyOwner { require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH"); rebateScale = _rebateScale; emit SetRebateScale(_rebateScale); } /** * @notice Set max * @dev Only owner * @param _rebateMax uint256 */ function setRebateMax(uint256 _rebateMax) external onlyOwner { require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); rebateMax = _rebateMax; emit SetRebateMax(_rebateMax); } /** * @notice Set the staking token * @param newStakingToken address Token to check balances on */ function setStakingToken(address newStakingToken) external onlyOwner { // Ensure the new staking token is not null require(newStakingToken != address(0), "INVALID_FEE_WALLET"); stakingToken = newStakingToken; emit SetStakingToken(newStakingToken); } /** * @notice Authorize a signer * @param signer address Wallet of the signer to authorize * @dev Emits an Authorize event */ function authorize(address signer) external override { require(signer != address(0), "SIGNER_INVALID"); authorized[msg.sender] = signer; emit Authorize(signer, msg.sender); } /** * @notice Revoke the signer * @dev Emits a Revoke event */ function revoke() external override { address tmp = authorized[msg.sender]; delete authorized[msg.sender]; emit Revoke(tmp, msg.sender); } /** * @notice Cancel one or more nonces * @dev Cancelled nonces are marked as used * @dev Emits a Cancel event * @dev Out of gas may occur in arrays of length > 400 * @param nonces uint256[] List of nonces to cancel */ function cancel(uint256[] calldata nonces) external override { for (uint256 i = 0; i < nonces.length; i++) { uint256 nonce = nonces[i]; if (_markNonceAsUsed(msg.sender, nonce)) { emit Cancel(nonce, msg.sender); } } } /** * @notice Validates Swap Order for any potential errors * @param senderWallet address Wallet that would send the order * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param enforceIdentity bool Require the maker to have a registered Signata Identity * @param checkRisk bool Require the maker to check the Chainlink Risk Oracle * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature * @return tuple of error count and bytes32[] memory array of error messages */ function check( address senderWallet, uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, bool enforceIdentity, bool checkRisk, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public view returns (uint256, bytes32[] memory) { bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT); Order memory order; uint256 errCount; order.nonce = nonce; order.expiry = expiry; order.signerWallet = signerWallet; order.signerToken = signerToken; order.signerAmount = signerAmount; order.enforceIdentity = enforceIdentity; order.checkRisk = checkRisk; order.senderToken = senderToken; order.senderAmount = senderAmount; order.v = v; order.r = r; order.s = s; order.senderWallet = senderWallet; bytes32 hashed = _getOrderHash( order.nonce, order.expiry, order.signerWallet, order.signerToken, order.signerAmount, order.enforceIdentity, order.checkRisk, order.senderWallet, order.senderToken, order.senderAmount ); address signatory = _getSignatory(hashed, order.v, order.r, order.s); if (signatory == address(0)) { errors[errCount] = "SIGNATURE_INVALID"; errCount++; } if (order.expiry < block.timestamp) { errors[errCount] = "EXPIRY_PASSED"; errCount++; } if ( order.signerWallet != signatory && authorized[order.signerWallet] != signatory ) { errors[errCount] = "UNAUTHORIZED"; errCount++; } else { if (nonceUsed(signatory, order.nonce)) { errors[errCount] = "NONCE_ALREADY_USED"; errCount++; } } uint256 signerBalance = IERC20(order.signerToken).balanceOf( order.signerWallet ); uint256 signerAllowance = IERC20(order.signerToken).allowance( order.signerWallet, address(this) ); uint256 feeAmount = order.signerAmount.mul(protocolFee).div(FEE_DIVISOR); if (signerAllowance < order.signerAmount + feeAmount) { errors[errCount] = "SIGNER_ALLOWANCE_LOW"; errCount++; } if (signerBalance < order.signerAmount + feeAmount) { errors[errCount] = "SIGNER_BALANCE_LOW"; errCount++; } return (errCount, errors); } /** * @notice Calculate output amount for an input score * @param stakingBalance uint256 * @param feeAmount uint256 */ function calculateDiscount(uint256 stakingBalance, uint256 feeAmount) public view returns (uint256) { uint256 divisor = (uint256(10)**rebateScale).add(stakingBalance); return rebateMax.mul(stakingBalance).mul(feeAmount).div(divisor).div(100); } /** * @notice Calculates and refers fee amount * @param wallet address * @param amount uint256 */ function calculateProtocolFee(address wallet, uint256 amount) public view override returns (uint256) { // Transfer fee from signer to feeWallet uint256 feeAmount = amount.mul(protocolFee).div(FEE_DIVISOR); if (feeAmount > 0) { uint256 discountAmount = calculateDiscount( IERC20(stakingToken).balanceOf(wallet), feeAmount ); return feeAmount - discountAmount; } return feeAmount; } /** * @notice Returns true if the nonce has been used * @param signer address Address of the signer * @param nonce uint256 Nonce being checked */ function nonceUsed(address signer, uint256 nonce) public view override returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1; } /** * @notice Returns the current chainId using the chainid opcode * @return id uint256 The chain id */ function getChainId() public view returns (uint256 id) { // no-inline-assembly assembly { id := chainid() } } /** * @notice Marks a nonce as used for the given signer * @param signer address Address of the signer for which to mark the nonce as used * @param nonce uint256 Nonce to be marked as used * @return bool True if the nonce was not marked as used already */ function _markNonceAsUsed(address signer, uint256 nonce) internal returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; uint256 group = _nonceGroups[signer][groupKey]; // If it is already used, return false if ((group >> indexInGroup) & 1 == 1) { return false; } _nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup); return true; } /** * @notice Checks Order Expiry, Nonce, Signature * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function _checkValidOrder( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, bool enforceIdentity, bool checkRisk, uint8 v, bytes32 r, bytes32 s ) internal { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); // Ensure the expiry is not passed require(expiry > block.timestamp, "EXPIRY_PASSED"); bytes32 hashed = _getOrderHash( nonce, expiry, signerWallet, signerToken, signerAmount, enforceIdentity, checkRisk, msg.sender, senderToken, senderAmount ); // Recover the signatory from the hash and signature address signatory = _getSignatory(hashed, v, r, s); // Ensure the signatory is not null require(signatory != address(0), "SIGNATURE_INVALID"); // Ensure the nonce is not yet used and if not mark it used require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED"); // Ensure the signatory is authorized by the signer wallet if (signerWallet != signatory) { require(authorized[signerWallet] == signatory, "UNAUTHORIZED"); } if (enforceIdentity) { // an unregistered address will throw "SignataIdentity: The identity must exist." signataIdentity.getDelegate(msg.sender); require( !signataIdentity.isLocked(msg.sender), "Veriswap: The sender's identity is locked." ); } if (checkRisk) { // TODO: drop in the chainlink integration here } } /** * @notice Hash order parameters * @param nonce uint256 * @param expiry uint256 * @param signerWallet address * @param signerToken address * @param signerAmount uint256 * @param senderToken address * @param senderAmount uint256 * @return bytes32 */ function _getOrderHash( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, bool enforceIdentity, bool checkRisk, address senderWallet, address senderToken, uint256 senderAmount ) internal view returns (bytes32) { return keccak256( abi.encode( ORDER_TYPEHASH, nonce, expiry, signerWallet, signerToken, signerAmount, enforceIdentity, checkRisk, protocolFee, senderWallet, senderToken, senderAmount ) ); } /** * @notice Recover the signatory from a signature * @param hash bytes32 * @param v uint8 * @param r bytes32 * @param s bytes32 */ function _getSignatory( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal view returns (address) { return ecrecover( keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)), v, r, s ); } /** * @notice Calculates and transfers protocol fee and rebate * @param sourceToken address * @param sourceWallet address * @param amount uint256 */ function _transferProtocolFee( address sourceToken, address sourceWallet, uint256 amount ) internal { // Transfer fee from signer to feeWallet uint256 feeAmount = amount.mul(protocolFee).div(FEE_DIVISOR); if (feeAmount > 0) { uint256 discountAmount = calculateDiscount( IERC20(stakingToken).balanceOf(msg.sender), feeAmount ); if (discountAmount > 0) { // Transfer fee from signer to sender IERC20(sourceToken).safeTransferFrom( sourceWallet, msg.sender, discountAmount ); // Transfer fee from signer to feeWallet IERC20(sourceToken).safeTransferFrom( sourceWallet, protocolFeeWallet, feeAmount - discountAmount ); } else { IERC20(sourceToken).safeTransferFrom( sourceWallet, protocolFeeWallet, feeAmount ); } } } }
* @notice Double mapping of signers to nonce groups to nonce states @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used/
) { require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE"); require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH"); require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); require(_stakingToken != address(0), "INVALID_STAKING_TOKEN"); uint256 currentChainId = getChainId(); DOMAIN_CHAIN_ID = currentChainId; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, DOMAIN_NAME, DOMAIN_VERSION, currentChainId, this ) ); protocolFee = _protocolFee; protocolFeeLight = _protocolFeeLight; protocolFeeWallet = _protocolFeeWallet; rebateScale = _rebateScale; rebateMax = _rebateMax; stakingToken = _stakingToken; signataIdentity = SignataIdentity(_signataIdentity); }
5,389,348
[ 1, 5265, 2874, 434, 1573, 414, 358, 7448, 3252, 358, 7448, 5493, 225, 1021, 7448, 1041, 353, 8470, 487, 7448, 342, 8303, 16, 1427, 1517, 1041, 434, 8303, 21210, 1661, 764, 4692, 326, 1967, 498, 225, 1021, 7448, 5493, 854, 3749, 487, 8303, 4125, 16, 364, 1517, 7448, 316, 326, 1041, 374, 4696, 2319, 471, 404, 4696, 1399, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 262, 288, 203, 565, 2583, 24899, 8373, 14667, 411, 478, 9383, 67, 2565, 26780, 916, 16, 315, 9347, 67, 8090, 41, 8863, 203, 565, 2583, 24899, 8373, 14667, 12128, 411, 478, 9383, 67, 2565, 26780, 916, 16, 315, 9347, 67, 8090, 41, 8863, 203, 565, 2583, 24899, 8373, 14667, 16936, 480, 1758, 12, 20, 3631, 315, 9347, 67, 8090, 41, 67, 59, 1013, 15146, 8863, 203, 565, 2583, 24899, 266, 70, 340, 5587, 1648, 4552, 67, 19378, 16, 315, 19378, 67, 4296, 51, 67, 29996, 8863, 203, 565, 2583, 24899, 266, 70, 340, 2747, 1648, 4552, 67, 3194, 19666, 2833, 16, 315, 6694, 67, 4296, 51, 67, 29996, 8863, 203, 565, 2583, 24899, 334, 6159, 1345, 480, 1758, 12, 20, 3631, 315, 9347, 67, 882, 14607, 1360, 67, 8412, 8863, 203, 203, 565, 2254, 5034, 783, 3893, 548, 273, 30170, 548, 5621, 203, 565, 27025, 67, 1792, 6964, 67, 734, 273, 783, 3893, 548, 31, 203, 565, 27025, 67, 4550, 273, 417, 24410, 581, 5034, 12, 203, 1377, 24126, 18, 3015, 12, 203, 3639, 27025, 67, 2399, 15920, 16, 203, 3639, 27025, 67, 1985, 16, 203, 3639, 27025, 67, 5757, 16, 203, 3639, 783, 3893, 548, 16, 203, 3639, 333, 203, 1377, 262, 203, 565, 11272, 203, 203, 565, 1771, 14667, 273, 389, 8373, 14667, 31, 203, 565, 1771, 14667, 12128, 273, 389, 8373, 14667, 12128, 31, 203, 565, 1771, 14667, 16936, 273, 389, 8373, 14667, 16936, 31, 203, 565, 283, 70, 340, 5587, 273, 389, 266, 70, 340, 5587, 31, 203, 565, 2 ]
pragma solidity ^0.4.24; // 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 OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: 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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/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; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/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/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/NectarToken.sol contract NectarToken is MintableToken { string public name = "Nectar"; string public symbol = "NCT"; uint8 public decimals = 18; bool public transfersEnabled = false; event TransfersEnabled(); // Disable transfers until after the sale modifier whenTransfersEnabled() { require(transfersEnabled, "Transfers not enabled"); _; } modifier whenTransfersNotEnabled() { require(!transfersEnabled, "Transfers enabled"); _; } function enableTransfers() public onlyOwner whenTransfersNotEnabled { transfersEnabled = true; emit TransfersEnabled(); } function transfer(address to, uint256 value) public whenTransfersEnabled returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenTransfersEnabled returns (bool) { return super.transferFrom(from, to, value); } // Approves and then calls the receiving contract function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); // Call the receiveApproval function on the contract you want to be notified. // This crafts the function signature manually so one doesn&#39;t have to include a contract in here just for this. // // receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) // // It is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. // solium-disable-next-line security/no-low-level-calls, indentation require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData), "receiveApproval failed"); return true; } } // File: contracts/OfferMultiSig.sol contract OfferMultiSig is Pausable { using SafeMath for uint256; string public constant NAME = "Offer MultiSig"; string public constant VERSION = "0.0.1"; uint256 public constant MIN_SETTLEMENT_PERIOD = 10; uint256 public constant MAX_SETTLEMENT_PERIOD = 3600; event CommunicationsSet( bytes32 websocketUri ); event OpenedAgreement( address _ambassador ); event CanceledAgreement( address _ambassador ); event JoinedAgreement( address _expert ); event ClosedAgreement( address _expert, address _ambassador ); event FundsDeposited( address _ambassador, address _expert, uint256 ambassadorBalance, uint256 expertBalance ); event StartedSettle( address initiator, uint sequence, uint settlementPeriodEnd ); event SettleStateChallenged( address challenger, uint sequence, uint settlementPeriodEnd ); address public nectarAddress; // Address of offer nectar token address public ambassador; // Address of first channel participant address public expert; // Address of second channel participant bool public isOpen = false; // true when both parties have joined bool public isPending = false; // true when waiting for counterparty to join agreement uint public settlementPeriodLength; // How long challengers have to reply to settle engagement uint public isClosed; // if the period has closed uint public sequence; // state nonce used in during settlement uint public isInSettlementState; // meta channel is in settling 1: Not settling 0 uint public settlementPeriodEnd; // The time when challenges are no longer accepted after bytes public state; // the current state bytes32 public websocketUri; // a geth node running whisper (shh) constructor(address _nectarAddress, address _ambassador, address _expert, uint _settlementPeriodLength) public { require(_ambassador != address(0), "No ambassador lib provided to constructor"); require(_expert != address(0), "No expert provided to constructor"); require(_nectarAddress != address(0), "No token provided to constructor"); // solium-disable-next-line indentation require(_settlementPeriodLength >= MIN_SETTLEMENT_PERIOD && _settlementPeriodLength <= MAX_SETTLEMENT_PERIOD, "Settlement period out of range"); ambassador = _ambassador; expert = _expert; settlementPeriodLength = _settlementPeriodLength; nectarAddress = _nectarAddress; } /** Function only callable by participants */ modifier onlyParticipants() { require(msg.sender == ambassador || msg.sender == expert, "msg.sender is not a participant"); _; } /** * Function called by ambassador to open channel with _expert * * @param _state inital offer state * @param _v the recovery id from signature of state * @param _r output of ECDSA signature of state * @param _s output of ECDSA signature of state */ function openAgreement(bytes _state, uint8 _v, bytes32 _r, bytes32 _s) public whenNotPaused { // require the channel is not open yet require(isOpen == false, "openAgreement already called, isOpen true"); require(isPending == false, "openAgreement already called, isPending true"); require(msg.sender == ambassador, "msg.sender is not the ambassador"); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(msg.sender == getPartyA(_state), "Party A does not match signature recovery"); // check the account opening a channel signed the initial state address initiator = getSig(_state, _v, _r, _s); require(ambassador == initiator, "Initiator in state is not the ambassador"); isPending = true; state = _state; open(_state); emit OpenedAgreement(ambassador); } /** * Function called by ambassador to cancel a channel that hasn&#39;t been joined yet */ function cancelAgreement() public whenNotPaused { // require the channel is not open yet require(isPending == true, "Only a channel in a pending state can be canceled"); require(msg.sender == ambassador, "Only an ambassador can cancel an agreement"); isPending = false; cancel(nectarAddress); emit CanceledAgreement(ambassador); } /** * Function called by expert to complete opening the channel with an ambassador defined in the _state * * @param _state offer state from ambassador * @param _v the recovery id from signature of state * @param _r output of ECDSA signature of state * @param _s output of ECDSA signature of state */ function joinAgreement(bytes _state, uint8 _v, bytes32 _r, bytes32 _s) public whenNotPaused { require(isOpen == false, "openAgreement already called, isOpen true"); require(msg.sender == expert, "msg.sender is not the expert"); require(isPending, "Offer not pending"); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); // check that the state is signed by the sender and sender is in the state address joiningParty = getSig(_state, _v, _r, _s); require(expert == joiningParty, "Joining party in state is not the expert"); // no longer allow joining functions to be called isOpen = true; isPending = false; join(state); emit JoinedAgreement(expert); } /** * Function called by ambassador to update balance and add to escrow * by default to escrows the allowed balance * @param _state offer state from ambassador * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties * @dev index 0 is the ambassador signature * @dev index 1 is the expert signature */ function depositFunds(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused { require(isOpen == true, "Tried adding funds to a closed msig wallet"); address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); // Require both signatures require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); state = _state; update(_state); emit FundsDeposited(_ambassador, _expert, getBalanceA(_state), getBalanceB(_state)); } /** * Function called by ambassador or expert to close a their channel after a dispute has timedout * * @param _state final offer state agreed on by both parties through dispute settlement * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties * @dev index 0 is the ambassador signature * @dev index 1 is the expert signature */ function closeAgreementWithTimeout(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused { address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(settlementPeriodEnd <= block.number, "Settlement period hasn&#39;t ended"); require(isClosed == 0, "Offer is closed"); require(isInSettlementState == 1, "Offer is not in settlement state"); require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); require(keccak256(state) == keccak256(_state), "State hash mismatch"); isClosed = 1; finalize(_state); isOpen = false; emit ClosedAgreement(_expert, _ambassador); } /** * Function called by ambassador or expert to close a their channel with close flag * * @param _state final offer state agreed on by both parties with close flag * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties * @dev index 0 is the ambassador signature * @dev index 1 is the expert signature */ function closeAgreement(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused { address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(isClosed == 0, "Offer is closed"); /// @dev make sure we&#39;re not in dispute require(isInSettlementState == 0, "Offer is in settlement state"); /// @dev must have close flag require(_isClosed(_state), "State did not have a signed close out state"); require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); isClosed = 1; state = _state; finalize(_state); isOpen = false; emit ClosedAgreement(_expert, _ambassador); } /** * Function called by ambassador or expert to start initalize a disputed settlement * using an agreed upon state. It starts a timeout for a reply using `settlementPeriodLength` * * @param _state offer state agreed on by both parties * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties */ function startSettle(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused { address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); require(isClosed == 0, "Offer is closed"); require(isInSettlementState == 0, "Offer is in settlement state"); state = _state; sequence = getSequence(_state); isInSettlementState = 1; settlementPeriodEnd = block.number.add(settlementPeriodLength); emit StartedSettle(msg.sender, sequence, settlementPeriodEnd); } /** * Function called by ambassador or expert to challenge a disputed state * The new state is accepted if it is signed by both parties and has a higher sequence number * * @param _state offer state agreed on by both parties * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties */ function challengeSettle(bytes _state, uint8[2] _sigV, bytes32[2] _sigR, bytes32[2] _sigS) public onlyParticipants whenNotPaused { address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); require(isInSettlementState == 1, "Offer is not in settlement state"); require(block.number < settlementPeriodEnd, "Settlement period has ended"); require(getSequence(_state) > sequence, "Sequence number is too old"); settlementPeriodEnd = block.number.add(settlementPeriodLength); state = _state; sequence = getSequence(_state); emit SettleStateChallenged(msg.sender, sequence, settlementPeriodEnd); } /** * Return when the settlement period is going to end. This is the amount of time * an ambassor or expert has to reply with a new state */ function getSettlementPeriodEnd() public view returns (uint) { return settlementPeriodEnd; } /** * Function to be called by ambassador to set comunication information * * @param _websocketUri uri of whisper node */ function setCommunicationUri(bytes32 _websocketUri) external whenNotPaused { require(msg.sender == ambassador, "msg.sender is not the ambassador"); websocketUri = _websocketUri; emit CommunicationsSet(websocketUri); } /** * Function called to get the state sequence/nonce * * @param _state offer state */ function getSequence(bytes _state) public pure returns (uint _seq) { // solium-disable-next-line security/no-inline-assembly assembly { _seq := mload(add(_state, 64)) } } function isChannelOpen() public view returns (bool) { return isOpen; } function getWebsocketUri() public view returns (bytes32) { return websocketUri; } /** * A utility function to check if both parties have signed * * @param _a ambassador address * @param _b expert address */ function _hasAllSigs(address _a, address _b) internal view returns (bool) { require(_a == ambassador && _b == expert, "Signatures do not match parties in state"); return true; } /** * A utility function to check for the closed flag in the offer state * * @param _state current offer state */ function _isClosed(bytes _state) internal pure returns (bool) { require(getCloseFlag(_state) == 1, "Offer is not closed"); return true; } function getCloseFlag(bytes _state) public pure returns (uint8 _flag) { // solium-disable-next-line security/no-inline-assembly assembly { _flag := mload(add(_state, 32)) } } function getPartyA(bytes _state) public pure returns (address _ambassador) { // solium-disable-next-line security/no-inline-assembly assembly { _ambassador := mload(add(_state, 96)) } } function getPartyB(bytes _state) public pure returns (address _expert) { // solium-disable-next-line security/no-inline-assembly assembly { _expert := mload(add(_state, 128)) } } function getBalanceA(bytes _state) public pure returns (uint256 _balanceA) { // solium-disable-next-line security/no-inline-assembly assembly { _balanceA := mload(add(_state, 192)) } } function getBalanceB(bytes _state) public pure returns (uint256 _balanceB) { // solium-disable-next-line security/no-inline-assembly assembly { _balanceB := mload(add(_state, 224)) } } function getTokenAddress(bytes _state) public pure returns (address _token) { // solium-disable-next-line security/no-inline-assembly assembly { _token := mload(add(_state, 256)) } } function getTotal(bytes _state) public pure returns (uint256) { uint256 _a = getBalanceA(_state); uint256 _b = getBalanceB(_state); return _a.add(_b); } function open(bytes _state) internal returns (bool) { require(msg.sender == getPartyA(_state), "Party A does not match signature recovery"); // get the token instance used to allow funds to msig NectarToken _t = NectarToken(getTokenAddress(_state)); // ensure the amount sent to open channel matches the signed state balance require(_t.allowance(getPartyA(_state), this) == getBalanceA(_state), "value does not match ambassador state balance"); // complete the tranfer of ambassador approved tokens require(_t.transferFrom(getPartyA(_state), this, getBalanceA(_state)), "failed tranfering approved balance from ambassador"); return true; } function join(bytes _state) internal view returns (bool) { // get the token instance used to allow funds to msig NectarToken _t = NectarToken(getTokenAddress(_state)); // ensure the amount sent to join channel matches the signed state balance require(msg.sender == getPartyB(_state), "Party B does not match signature recovery"); // Require bonded is the sum of balances in state require(getTotal(_state) == _t.balanceOf(this), "token total deposited does not match state balance"); return true; } function update(bytes _state) internal returns (bool) { // get the token instance used to allow funds to msig NectarToken _t = NectarToken(getTokenAddress(_state)); if(_t.allowance(getPartyA(_state), this) > 0) { require(_t.transferFrom(getPartyA(_state), this, _t.allowance(getPartyA(_state), this)), "failed transfering deposit from party A to contract"); } require(getTotal(_state) == _t.balanceOf(this), "token total deposited does not match state balance"); } function cancel(address tokenAddress) internal returns (bool) { NectarToken _t = NectarToken(tokenAddress); return _t.transfer(msg.sender, _t.balanceOf(this)); } /** * Function called by closeAgreementWithTimeout or closeAgreement to disperse payouts * * @param _state final offer state agreed on by both parties with close flag */ function finalize(bytes _state) internal returns (bool) { address _a = getPartyA(_state); address _b = getPartyB(_state); NectarToken _t = NectarToken(getTokenAddress(_state)); require(getTotal(_state) == _t.balanceOf(this), "tried finalizing token state that does not match bonded value"); require(_t.transfer(_a, getBalanceA(_state)), "failed transfering balance to party A"); require(_t.transfer(_b, getBalanceB(_state)), "failed transfering balance to party B"); } /** * A utility function to return the address of the person that signed the state * * @param _state offer state that was signed * @param _v the recovery id from signature of state by both parties * @param _r output of ECDSA signature of state by both parties * @param _s output of ECDSA signature of state by both parties */ function getSig(bytes _state, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 h = keccak256(_state); bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, h)); address a = ecrecover(prefixedHash, _v, _r, _s); return a; } } // File: contracts/OfferRegistry.sol /// @title Creates new Offer Channel contracts and keeps track of them contract OfferRegistry is Pausable { struct OfferChannel { address msig; address ambassador; address expert; } event InitializedChannel( address msig, address ambassador, address expert, uint128 guid ); uint128[] public channelsGuids; mapping (bytes32 => address) public participantsToChannel; mapping (uint128 => OfferChannel) public guidToChannel; address public nectarAddress; constructor(address _nectarAddress) public { require(_nectarAddress != address(0), "Invalid token address"); nectarAddress = _nectarAddress; } /** * Function called by ambassador to initialize an offer contract * It deploys a new offer multi sig and saves it for each participant * * @param _ambassador address of ambassador * @param _expert address of expert * @param _settlementPeriodLength how long the parties have to dispute the settlement offer channel */ function initializeOfferChannel(uint128 guid, address _ambassador, address _expert, uint _settlementPeriodLength) external whenNotPaused { require(address(0) != _expert, "Invalid expert address"); require(address(0) != _ambassador, "Invalid ambassador address"); require(msg.sender == _ambassador, "Initializer isn&#39;t ambassador"); require(guidToChannel[guid].msig == address(0), "GUID already in use"); bytes32 key = getParticipantsHash(_ambassador, _expert); if (participantsToChannel[key] != address(0)) { /// @dev check to make sure the participants don&#39;t already have an open channel // solium-disable-next-line indentation require(OfferMultiSig(participantsToChannel[key]).isChannelOpen() == false, "Channel already exists between parties"); } address msig = new OfferMultiSig(nectarAddress, _ambassador, _expert, _settlementPeriodLength); participantsToChannel[key] = msig; guidToChannel[guid].msig = msig; guidToChannel[guid].ambassador = _ambassador; guidToChannel[guid].expert = _expert; channelsGuids.push(guid); emit InitializedChannel(msig, _ambassador, _expert, guid); } /** * Get the total number of offer channels tracked by the contract * * @return total number of offer channels */ function getNumberOfOffers() external view returns (uint) { return channelsGuids.length; } /** * Function to get channel participants are on * * @param _ambassador the address of ambassador * @param _expert the address of ambassador */ function getParticipantsChannel(address _ambassador, address _expert) external view returns (address) { bytes32 key = getParticipantsHash(_ambassador, _expert); require(participantsToChannel[key] != address(0), "Channel does not exist between parties"); return participantsToChannel[key]; } /** * Gets all the created channelsGuids * * @return list of every channel registered */ function getChannelsGuids() external view returns (address[]) { require(channelsGuids.length != 0, "No channels initialized"); address[] memory registeredChannelsGuids = new address[](channelsGuids.length); for (uint i = 0; i < channelsGuids.length; i++) { registeredChannelsGuids[i] = channelsGuids[i]; } return registeredChannelsGuids; } /** * Pause all channels * * @return list of every channel registered */ function pauseChannels() external onlyOwner whenNotPaused { require(channelsGuids.length != 0, "No channels initialized"); pause(); for (uint i = 0; i < channelsGuids.length; i++) { OfferMultiSig(guidToChannel[channelsGuids[i]].msig).pause(); } } /** * Unpause all channels * * @return list of every channel registered */ function unpauseChannels() external onlyOwner whenPaused { require(channelsGuids.length != 0, "No channels initialized"); for (uint i = 0; i < channelsGuids.length; i++) { OfferMultiSig(guidToChannel[channelsGuids[i]].msig).unpause(); } } /** * Return offer information from state * * @return list of every channel registered * @param _state offer state agreed on by both parties */ function getOfferState( bytes _state ) public pure returns ( bytes32 _guid, uint256 _nonce, uint256 _amount, address _msigAddress, uint256 _balanceA, uint256 _balanceB, address _ambassador, address _expert, uint256 _isClosed, address _token, uint256 _mask, uint256 _assertion ) { // solium-disable-next-line security/no-inline-assembly assembly { _guid := mload(add(_state, 288)) // [256-287] - a globally-unique identifier for the listing _nonce:= mload(add(_state, 64)) // [32-63] - the sequence of state _amount := mload(add(_state, 320)) // [288-319] - the offer amount awarded to expert for responses _msigAddress := mload(add(_state, 160)) // [128-159] - msig address where funds and offer are managed _balanceA := mload(add(_state,192)) // [160-191] balance in nectar for ambassador _balanceB := mload(add(_state,224)) // [192-223] balance in nectar for expert _ambassador := mload(add(_state, 96)) // [64-95] - offer&#39;s ambassador address _expert := mload(add(_state, 128)) // [96-127] - offer&#39;s expert address _isClosed := mload(add(_state, 32)) // [0-31] - 0 or 1 for if the state is marked as closed _token := mload(add(_state, 256)) // [224-255] - nectar token address _mask := mload(add(_state, 480)) // [448-479] - assertion mask _assertion := mload(add(_state, 512)) // [480-511] - assertions from expert } } // Internals /** * Utility function to get hash * * @param _ambassador address of ambassador * @param _expert address of expert * @return hash of ambassador and expert */ function getParticipantsHash(address _ambassador, address _expert) internal pure returns (bytes32) { string memory str_ambassador = toString(_ambassador); string memory str_expert = toString(_expert); return keccak256(abi.encodePacked(strConcat(str_ambassador, str_expert))); } function toString(address x) internal pure returns (string) { bytes memory b = new bytes(20); for (uint i = 0; i < 20; i++) { b[i] = byte(uint8(uint(x) / (2**(8*(19 - i))))); } return string(b); } function strConcat(string _a, string _b) internal pure returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory abcde = new string(_ba.length + _bb.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } return string(babcde); } /** Disable usage of the fallback function */ function() public payable { revert("Do not allow sending Eth to this contract"); } }
solium-disable-next-line security/no-inline-assembly
function getPartyB(bytes _state) public pure returns (address _expert) { assembly { _expert := mload(add(_state, 128)) } }
6,495,892
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 7325, 38, 12, 3890, 389, 2019, 13, 1071, 16618, 1135, 261, 2867, 389, 338, 672, 13, 288, 203, 3639, 19931, 288, 203, 5411, 389, 338, 672, 519, 312, 945, 12, 1289, 24899, 2019, 16, 8038, 3719, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-16 */ // SPDX-License-Identifier: SimPL-2.0 pragma solidity ^0.6.2; contract ToBeElonMusk { string public name = "ToBeElonMusk"; string public symbol = "BEMUSK"; uint8 public decimals = 18; // from WETH event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); event DepositTo(address indexed src, address indexed dst, uint toLevel, uint wad); event NewUser(address indexed src, address indexed parent); event Upgrade(address indexed src, uint toLevel); event MissOrder(address indexed src, address indexed dst, uint toLevel); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; // main data mapping (address => uint) public userLevel; // user => level mapping (address => address) public userTree; // child => parent mapping (address => uint) public childrenCount; // parnet => childrenCount mapping (address => mapping (uint => uint)) public userLevelReceivedAmount; // {user => {level => amount}} mapping (address => mapping (uint => uint)) public userLevelReceivedOrderCount; // {user => {level => success order num}} mapping (address => mapping (uint => uint)) public userLevelMissedOrderCount; // {parent => {level => missed order num}} // address[9] public initedUser; // 9 address from level 1-> 9 address public king; // level 9 address public farmer; // level 1 uint public price; uint public maxLevel; address private owner; uint private maxLoopTimes; bool public stopped = false; // stoppable modifier stoppable() { require(!stopped); _; } function stop() public onlyOwner { stopped = true; } function start() public onlyOwner { stopped = false; } modifier onlyOwner() { require( msg.sender == owner, "Only owner can call this." ); _; } // constructor () public { // owner = msg.sender; // } constructor (address[] memory _initedUser, uint _price) public { owner = msg.sender; init(_initedUser, _price); } function init (address[] memory _initedUser, uint _price) public onlyOwner { require(_initedUser.length >= 5, 'inited user error'); initPrice(_price); maxLevel = _initedUser.length; maxLoopTimes = maxLevel; king = _initedUser[0]; farmer = _initedUser[maxLevel - 1]; address parent = _initedUser[0]; userLevel[parent] = maxLevel; for (uint i = 1; i < maxLevel; i++) { address cur = _initedUser[i]; userLevel[cur] = maxLevel - i; userTree[cur] = parent; childrenCount[parent] += 1; parent = cur; } } function initPrice (uint _price) public onlyOwner { require(_price > 0, 'price error'); price = _price; } function findMyKing (address cur) view private returns (address) { if (cur == farmer) { return king; } // for limited loop i uint i = 0; address parent = cur; while(i++ < maxLoopTimes) { parent = userTree[parent]; if (userLevel[parent] == maxLevel) { return parent; } } return king; } function depositTo (address to, uint toLevel, uint value) private { balanceOf[to] += value; uint level = userLevel[to]; userLevelReceivedAmount[to][level] += value; userLevelReceivedOrderCount[to][level] += 1; emit DepositTo(msg.sender, to, toLevel, value); } function missOrder (address to, uint level) private { userLevelMissedOrderCount[to][level] += 1; emit MissOrder(msg.sender, to, level); } function isFull (address to, uint level) view private returns (bool) { return userLevelReceivedAmount[to][level] >= maxReceiveAtLevel(level); // 3**level * price; } function maxReceiveAtLevel (uint level) view private returns (uint) { return 3**level * price; } function canTotalReceive () view private returns (uint) { uint total = 0; for (uint level = 1; level <= maxLevel; level++) { total += maxReceiveAtLevel(level); } return total; } function payForUpgrade (address me, uint value) private returns (bool) { require(value == price && price != 0, 'value error'); uint myLevel = userLevel[me]; uint toLevel = myLevel + 1; require(toLevel <= maxLevel, 'cannot upgrade'); require (!(toLevel == 2 && userLevelReceivedOrderCount[me][1] < 3), 'to upgrade level 2, need at least 3 children'); uint i = 0; address parent = me; bool found = false; while(i++ < maxLoopTimes) { parent = userTree[parent]; if (parent == address(0)) { break; } if (userLevel[parent] == toLevel && !isFull(parent, toLevel)) { found = true; break; } else { missOrder(parent, toLevel); } } if (!found) { parent = king; } depositTo(parent, toLevel, value); userLevel[me] = toLevel; emit Upgrade(me, toLevel); return true; } function payForNew (address me, address to, uint value) private returns (bool) { require(value == price * 2 && price != 0, 'value error'); if (to == address(0) || me == to || userLevel[to] == 0) { to = farmer; } address myKing = findMyKing(to); depositTo(to, 1, value/2); depositTo(myKing, 1, value/2); userLevel[me] = 1; userTree[me] = to; childrenCount[to] += 1; emit NewUser(me, to); return true; } // pay to contract direct // function() public payable { // pay(address(0)); // } function pay(address to) public payable stoppable returns (address) { address me = msg.sender; // old user if (userLevel[me] > 0) { payForUpgrade(me, msg.value); } // new user else { payForNew(me, to, msg.value); } return me; } function deposit() public payable stoppable { require(msg.value > 0); balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint wad) public stoppable { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return address(this).balance; } function approve(address guy, uint wad) public stoppable returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public stoppable returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-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; } }
{user => {level => success order num}}
mapping (address => mapping (uint => uint)) public userLevelReceivedOrderCount;
7,800,789
[ 1, 95, 1355, 516, 288, 2815, 516, 2216, 1353, 818, 9090, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 2874, 261, 11890, 516, 2254, 3719, 377, 1071, 225, 729, 2355, 8872, 2448, 1380, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xFBB1d40a7B3E553c510008c9bef1889015aC4965/sources/contracts/lending/tokens/cErc20ModifiedDelegator.sol
* @notice Accrues interest and adds reserves by transferring from admin @param addAmount Amount of reserves to add @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function _addReserves(uint256 addAmount) external returns (uint256) { bytes memory data = delegateToImplementation( abi.encodeWithSignature("_addReserves(uint256)", addAmount) ); return abi.decode(data, (uint256)); }
17,168,802
[ 1, 8973, 86, 3610, 16513, 471, 4831, 400, 264, 3324, 635, 906, 74, 20245, 628, 3981, 225, 527, 6275, 16811, 434, 400, 264, 3324, 358, 527, 327, 2254, 374, 33, 4768, 16, 3541, 279, 5166, 261, 5946, 1068, 13289, 18, 18281, 364, 3189, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 1289, 607, 264, 3324, 12, 11890, 5034, 527, 6275, 13, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 565, 1731, 3778, 501, 273, 7152, 774, 13621, 12, 203, 1377, 24126, 18, 3015, 1190, 5374, 2932, 67, 1289, 607, 264, 3324, 12, 11890, 5034, 2225, 16, 527, 6275, 13, 203, 565, 11272, 203, 565, 327, 24126, 18, 3922, 12, 892, 16, 261, 11890, 5034, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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; // 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: UNLICENSED pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./abstract/Ownable.sol"; import "./libraries/SafeERC20.sol"; /// @title PrivateSaleA /// @dev A token sale contract that accepts only desired USD stable coins as a payment. Blocks any direct ETH deposits. contract PrivateSaleA is Ownable { using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; // token sale beneficiary address public beneficiary; // token sale limits per account in USD with 2 decimals (cents) uint256 public minPerAccount; uint256 public maxPerAccount; // cap in USD for token sale with 2 decimals (cents) uint256 public cap; // timestamp and duration are expressed in UNIX time, the same units as block.timestamp uint256 public startTime; uint256 public duration; // used to prevent gas usage when sale is ended bool private _ended; // account balance in USD with 2 decimals (cents) mapping(address => uint256) public balances; EnumerableSet.AddressSet private _participants; struct ParticipantData { address _address; uint256 _balance; } // collected stable coins balances mapping(address => uint256) private _deposited; // collected amount in USD with 2 decimals (cents) uint256 public collected; // whitelist users in rounds mapping(uint256 => mapping(address => bool)) public whitelisted; uint256 public whitelistRound = 1; bool public whitelistedOnly = true; // list of supported stable coins EnumerableSet.AddressSet private stableCoins; event WhitelistChanged(bool newEnabled); event WhitelistRoundChanged(uint256 round); event Purchased(address indexed purchaser, uint256 amount); /// @dev creates a token sale contract that accepts only USD stable coins /// @param _owner address of the owner /// @param _beneficiary address of the owner /// @param _minPerAccount min limit in USD cents that account needs to spend /// @param _maxPerAccount max allocation in USD cents per account /// @param _cap sale limit amount in USD cents /// @param _startTime the time (as Unix time) of sale start /// @param _duration duration in seconds of token sale /// @param _stableCoinsAddresses array of ERC20 token addresses of stable coins accepted in the sale constructor( address _owner, address _beneficiary, uint256 _minPerAccount, uint256 _maxPerAccount, uint256 _cap, uint256 _startTime, uint256 _duration, address[] memory _stableCoinsAddresses ) Ownable(_owner) { require(_beneficiary != address(0), "Sale: zero address"); require(_cap > 0, "Sale: Cap is 0"); require(_duration > 0, "Sale: Duration is 0"); require(_startTime + _duration > block.timestamp, "Sale: Final time is before current time"); beneficiary = _beneficiary; minPerAccount = _minPerAccount; maxPerAccount = _maxPerAccount; cap = _cap; startTime = _startTime; duration = _duration; for (uint256 i; i < _stableCoinsAddresses.length; i++) { stableCoins.add(_stableCoinsAddresses[i]); } } // ----------------------------------------------------------------------- // GETTERS // ----------------------------------------------------------------------- /// @return the end time of the sale function endTime() external view returns (uint256) { return startTime + duration; } /// @return the balance of the account in USD cents function balanceOf(address account) external view returns (uint256) { return balances[account]; } /// @return the max allocation for account function maxAllocationOf(address account) external view returns (uint256) { if (!whitelistedOnly || whitelisted[whitelistRound][account]) { return maxPerAccount; } else { return 0; } } /// @return the amount in USD cents of remaining allocation function remainingAllocation(address account) external view returns (uint256) { if (!whitelistedOnly || whitelisted[whitelistRound][account]) { if (maxPerAccount > 0) { return maxPerAccount - balances[account]; } else { return cap - collected; } } else { return 0; } } /// @return information if account is whitelisted function isWhitelisted(address account) external view returns (bool) { if (whitelistedOnly) { return whitelisted[whitelistRound][account]; } else { return true; } } /// @return addresses with all stable coins supported in the sale function acceptableStableCoins() external view returns (address[] memory) { uint256 length = stableCoins.length(); address[] memory addresses = new address[](length); for (uint256 i = 0; i < length; i++) { addresses[i] = stableCoins.at(i); } return addresses; } /// @return info if sale is still ongoing function isLive() public view returns (bool) { return !_ended && block.timestamp > startTime && block.timestamp < startTime + duration; } function getParticipantsNumber() external view returns (uint256) { return _participants.length(); } /// @return participants data at index function getParticipantDataAt(uint256 index) external view returns (ParticipantData memory) { require(index < _participants.length(), "Incorrect index"); address pAddress = _participants.at(index); ParticipantData memory data = ParticipantData(pAddress, balances[pAddress]); return data; } /// @return participants data in range function getParticipantsDataInRange(uint256 from, uint256 to) external view returns (ParticipantData[] memory) { require(from <= to, "Incorrect range"); require(to < _participants.length(), "Incorrect range"); uint256 length = to - from + 1; ParticipantData[] memory data = new ParticipantData[](length); for (uint256 i; i < length; i++) { address pAddress = _participants.at(i + from); data[i] = ParticipantData(pAddress, balances[pAddress]); } return data; } // ----------------------------------------------------------------------- // INTERNAL // ----------------------------------------------------------------------- function _isBalanceSufficient(uint256 _amount) private view returns (bool) { return _amount + collected <= cap; } // ----------------------------------------------------------------------- // MODIFIERS // ----------------------------------------------------------------------- modifier onlyBeneficiary() { require(msg.sender == beneficiary, "Sale: Caller is not the beneficiary"); _; } modifier onlyWhitelisted() { require(!whitelistedOnly || whitelisted[whitelistRound][msg.sender], "Sale: Account is not whitelisted"); _; } modifier isOngoing() { require(isLive(), "Sale: Sale is not active"); _; } modifier isEnded() { require(_ended || block.timestamp > startTime + duration, "Sale: Not ended"); _; } // ----------------------------------------------------------------------- // SETTERS // ----------------------------------------------------------------------- /// @notice buy tokens using USD stable coins /// @dev use approve/transferFrom flow /// @param stableCoinAddress stable coin token address /// @param amount amount of USD cents function buyWith(address stableCoinAddress, uint256 amount) external isOngoing onlyWhitelisted { require(stableCoins.contains(stableCoinAddress), "Sale: Stable coin not supported"); require(amount > 0, "Sale: Amount is 0"); require(_isBalanceSufficient(amount), "Sale: Insufficient remaining amount"); require(amount + balances[msg.sender] >= minPerAccount, "Sale: Amount too low"); require(maxPerAccount == 0 || balances[msg.sender] + amount <= maxPerAccount, "Sale: Amount too high"); uint8 decimals = IERC20(stableCoinAddress).safeDecimals(); uint256 stableCoinUnits = amount * (10**(decimals - 2)); // solhint-disable-next-line max-line-length require(IERC20(stableCoinAddress).allowance(msg.sender, address(this)) >= stableCoinUnits, "Sale: Insufficient stable coin allowance"); IERC20(stableCoinAddress).safeTransferFrom(msg.sender, stableCoinUnits); balances[msg.sender] += amount; collected += amount; _deposited[stableCoinAddress] += stableCoinUnits; if (!_participants.contains(msg.sender)) { _participants.add(msg.sender); } emit Purchased(msg.sender, amount); } function endPresale() external onlyOwner { require(collected >= cap, "Sale: Limit not reached"); _ended = true; } function withdrawFunds() external onlyBeneficiary isEnded { _ended = true; uint256 amount; for (uint256 i; i < stableCoins.length(); i++) { address stableCoin = address(stableCoins.at(i)); amount = IERC20(stableCoin).balanceOf(address(this)); if (amount > 0) { IERC20(stableCoin).safeTransfer(beneficiary, amount); } } } function recoverErc20(address token) external onlyOwner { uint256 amount = IERC20(token).balanceOf(address(this)); amount -= _deposited[token]; if (amount > 0) { IERC20(token).safeTransfer(owner, amount); } } function recoverEth() external onlyOwner isEnded { payable(owner).transfer(address(this).balance); } function setBeneficiary(address newBeneficiary) public onlyOwner { require(newBeneficiary != address(0), "Sale: zero address"); beneficiary = newBeneficiary; } function setWhitelistedOnly(bool enabled) public onlyOwner { whitelistedOnly = enabled; emit WhitelistChanged(enabled); } function setWhitelistRound(uint256 round) public onlyOwner { whitelistRound = round; emit WhitelistRoundChanged(round); } function addWhitelistedAddresses(address[] calldata addresses) external onlyOwner { for (uint256 i; i < addresses.length; i++) { whitelisted[whitelistRound][addresses[i]] = true; } } } // SPDX-License-Identifier: MIT // Source: https://github.com/boringcrypto/BoringSolidity/blob/master/contracts/BoringOwnable.sol pragma solidity ^0.8.4; abstract contract OwnableData { address public owner; address public pendingOwner; } abstract contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address _owner) { require(_owner != address(0), "Ownable: zero address"); owner = _owner; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. function transferOwnership(address newOwner, bool direct) public onlyOwner { if (direct) { // Checks require(newOwner != address(0), "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); // EIP 2612 // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address owner) external view returns (uint256); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/IERC20.sol"; library SafeERC20 { function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } function safeTransfer(IERC20 token, address to, uint256 amount) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed"); } function safeTransferFrom(IERC20 token, address from, uint256 amount) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed"); } }
collected stable coins balances
mapping(address => uint256) private _deposited;
1,486,352
[ 1, 14676, 329, 14114, 276, 9896, 324, 26488, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 323, 1724, 329, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import {ECCMath} from "./ECCMath.sol"; interface CurveInterface { function getOrder() external view returns(uint order); function validateSignature(bytes32 message, uint[2] rs, uint[2] Q) external view returns (bool); function computePublicKey(uint priv) external view returns(uint[2] Q); } /** * @title Particular curve implementation * * Based on reworked ECCMath from Andreas Olofsson using modern precompiles * and his _add, _double and _add implementations. Added "toAffine" public method for convenience. * * Performs curve arithmetics and verifies signatures. * * @author Alexander Vlasov ([email protected]). */ contract Curve { // Field size uint public pp; // Base point (generator) G uint public Gx; uint public Gy; // Order of G uint public nn; // Curve parameters uint public aa; uint public bb; // Cofactor uint public hh; // Maximum value of s uint public lowSmax; uint[3] public pointOfInfinity = [0, 1, 0]; constructor (uint256 fieldSize, uint256 groupOrder, uint256 lowS, uint256 cofactor, uint256[2] generator, uint256 a, uint256 b) public { pp = fieldSize; nn = groupOrder; lowSmax = lowS; hh = cofactor; Gx = generator[0]; Gy = generator[1]; aa = a; bb = b; uint det = mulmod(a,a,fieldSize); //a^2 det = mulmod(det,a,fieldSize); //a^3 det = mulmod(4,det,fieldSize); //4*a^3 uint det2 = mulmod(b,b,fieldSize); //b^2 det2 = mulmod(27,det2,fieldSize); //27*b^2 require(addmod(det, det2, fieldSize) != 0); // 4*a^3 + 27*b^2 != 0 if (lowSmax == 0) { lowSmax = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; } } function getPointOfInfinity() public view returns (uint[3] Q) { return pointOfInfinity; } function getOrder() public view returns(uint order) { return nn; } // Point addition, P + Q // inData: Px, Py, Pz, Qx, Qy, Qz // outData: Rx, Ry, Rz function _add(uint[3] P, uint[3] Q) public view returns (uint[3] R) { if(P[2] == 0) return Q; if(Q[2] == 0) return P; uint p = pp; uint[4] memory zs; // Pz^2, Pz^3, Qz^2, Qz^3 zs[0] = mulmod(P[2], P[2], p); zs[1] = mulmod(P[2], zs[0], p); zs[2] = mulmod(Q[2], Q[2], p); zs[3] = mulmod(Q[2], zs[2], p); uint[4] memory us; us[0] = mulmod(P[0], zs[2], p); us[1] = mulmod(P[1], zs[3], p); us[2] = mulmod(Q[0], zs[0], p); us[3] = mulmod(Q[1], zs[1], p); // Pu, Ps, Qu, Qs if (us[0] == us[2]) { if (us[1] != us[3]) return pointOfInfinity; else { return _double(P); } } uint h = addmod(us[2], p - us[0], p); uint r = addmod(us[3], p - us[1], p); uint h2 = mulmod(h, h, p); uint h3 = mulmod(h2, h, p); uint Rx = addmod(mulmod(r, r, p), p - h3, p); uint uh2 = mulmod(us[0], h2, p); Rx = addmod(Rx, p - mulmod(2, uh2, p), p); R[0] = Rx; R[1] = mulmod(r, addmod(uh2, p - Rx, p), p); R[1] = addmod(R[1], p - mulmod(us[1], h3, p), p); R[2] = mulmod(h, mulmod(P[2], Q[2], p), p); return R; } // Point addition, P + Q. P Jacobian, Q affine. // inData: Px, Py, Pz, Qx, Qy // outData: Rx, Ry, Rz function _addMixed(uint[3] P, uint[2] Q) public view returns (uint[3] R) { if(P[2] == 0) return [Q[0], Q[1], 1]; if(Q[1] == 0) return P; uint p = pp; uint[2] memory zs; // Pz^2, Pz^3, Qz^2, Qz^3 zs[0] = mulmod(P[2], P[2], p); zs[1] = mulmod(P[2], zs[0], p); uint[4] memory us = [ P[0], P[1], mulmod(Q[0], zs[0], p), mulmod(Q[1], zs[1], p) ]; // Pu, Ps, Qu, Qs if (us[0] == us[2]) { if (us[1] != us[3]) { return pointOfInfinity; } else { return _double(P); } } uint h = addmod(us[2], p - us[0], p); uint r = addmod(us[3], p - us[1], p); uint h2 = mulmod(h, h, p); uint h3 = mulmod(h2, h, p); uint Rx = addmod(mulmod(r, r, p), p - h3, p); Rx = addmod(Rx, p - mulmod(2, mulmod(us[0], h2, p), p), p); R[0] = Rx; R[1] = mulmod(r, addmod(mulmod(us[0], h2, p), p - Rx, p), p); R[1] = addmod(R[1], p - mulmod(us[1], h3, p), p); R[2] = mulmod(h, P[2], p); return R; } // Point doubling, 2*P // Params: Px, Py, Pz // Not concerned about the 1 extra mulmod. function _double(uint[3] P) public view returns (uint[3] Q) { uint p = pp; uint a = aa; if (P[2] == 0) return pointOfInfinity; uint Px = P[0]; uint Py = P[1]; uint Py2 = mulmod(Py, Py, p); uint s = mulmod(4, mulmod(Px, Py2, p), p); uint m = mulmod(3, mulmod(Px, Px, p), p); if (a != 0) { uint z2 = mulmod(P[2], P[2], p); m = addmod(m, mulmod(mulmod(z2, z2, p), a, p), p); } uint Qx = addmod(mulmod(m, m, p), p - addmod(s, s, p), p); Q[0] = Qx; Q[1] = addmod(mulmod(m, addmod(s, p - Qx, p), p), p - mulmod(8, mulmod(Py2, Py2, p), p), p); Q[2] = mulmod(2, mulmod(Py, P[2], p), p); return Q; } // Multiplication dP. P affine, wNAF: w=5 // Params: d, Px, Py // Output: Jacobian Q function _mul(uint d, uint[2] P) public view returns (uint[3] Q) { uint p = pp; if (d == 0) { return pointOfInfinity; } uint dwPtr; // points to array of NAF coefficients. uint i; // wNAF assembly { let dm := 0 dwPtr := mload(0x40) mstore(0x40, add(dwPtr, 512)) // Should lower this. loop: jumpi(loop_end, iszero(d)) jumpi(even, iszero(and(d, 1))) dm := mod(d, 32) mstore8(add(dwPtr, i), dm) // Don't store as signed - convert when reading. d := add(sub(d, dm), mul(gt(dm, 16), 32)) even: d := div(d, 2) i := add(i, 1) jump(loop) loop_end: } // Pre calculation uint[3][8] memory PREC; // P, 3P, 5P, 7P, 9P, 11P, 13P, 15P PREC[0] = [P[0], P[1], 1]; uint[3] memory X = _double(PREC[0]); PREC[1] = _addMixed(X, P); PREC[2] = _add(X, PREC[1]); PREC[3] = _add(X, PREC[2]); PREC[4] = _add(X, PREC[3]); PREC[5] = _add(X, PREC[4]); PREC[6] = _add(X, PREC[5]); PREC[7] = _add(X, PREC[6]); // Mult loop while(i > 0) { uint dj; uint pIdx; i--; assembly { dj := byte(0, mload(add(dwPtr, i))) } Q = _double(Q); if (dj > 16) { pIdx = (31 - dj) / 2; // These are the "negative ones", so invert y. Q = _add(Q, [PREC[pIdx][0], p - PREC[pIdx][1], PREC[pIdx][2] ]); } else if (dj > 0) { pIdx = (dj - 1) / 2; Q = _add(Q, [PREC[pIdx][0], PREC[pIdx][1], PREC[pIdx][2] ]); } if (Q[0] == pointOfInfinity[0] && Q[1] == pointOfInfinity[1] && Q[2] == pointOfInfinity[2]) { return Q; } } return Q; } function onCurve(uint[2] P) public view returns (bool) { uint p = pp; uint a = aa; uint b = bb; if (0 == P[0] || P[0] == p || 0 == P[1] || P[1] == p) return false; uint LHS = mulmod(P[1], P[1], p); // y^2 uint RHS = mulmod(mulmod(P[0], P[0], p), P[0], p); // x^3 if (a != 0) { RHS = addmod(RHS, mulmod(P[0], a, p), p); // x^3 + a*x } if (b != 0) { RHS = addmod(RHS, b, p); // x^3 + a*x + b } return LHS == RHS; } /// @dev See Curve.isPubKey function isPubKey(uint[2] P) public view returns (bool isPK) { isPK = onCurve(P); return isPK; } /// @dev See Curve.validateSignature function validateSignature(bytes32 message, uint[2] rs, uint[2] Q) public view returns (bool) { uint n = nn; uint p = pp; if(rs[0] == 0 || rs[0] >= n || rs[1] == 0 || rs[1] > lowSmax) return false; if (!isPubKey(Q)) return false; uint sInv = ECCMath.invmod(rs[1], n); uint[3] memory u1G = _mul(mulmod(uint(message), sInv, n), [Gx, Gy]); uint[3] memory u2Q = _mul(mulmod(rs[0], sInv, n), Q); uint[3] memory P = _add(u1G, u2Q); if (P[2] == 0) return false; uint Px = ECCMath.invmod(P[2], p); // need Px/Pz^2 Px = mulmod(P[0], mulmod(Px, Px, p), p); return Px % n == rs[0]; } function computePublicKey(uint priv) public view returns(uint[2] Q) { uint[2] memory generator = [Gx, Gy]; uint[3] memory P = _mul(priv, generator); return toAffine(P); } // @dev Only used on the local node function createSignature(bytes32 message, uint k, uint priv) public view returns (uint r, uint s) { uint p = pp; uint n = nn; uint[2] memory generator = [Gx, Gy]; uint[3] memory P = _mul(k, generator); ECCMath.toZ1(P, p); r = P[0] % n; s = mulmod(priv, r, n); s = addmod(uint(message), s, n); uint k_1 = ECCMath.invmod(k, n); s = mulmod(k_1, s, n); return (r, s); } /// @dev See Curve.compress function compress(uint[2] P) public pure returns (uint8 yBit, uint x) { x = P[0]; yBit = P[1] & 1 == 1 ? 1 : 0; return (yBit, x); } /// @dev See Curve.decompress function decompress(uint8 yBit, uint x) public view returns (uint[2] P) { uint p = pp; uint a = aa; uint b = bb; uint y2 = mulmod(x, mulmod(x, x, p), p); if (a != 0) { y2 = addmod(y2, mulmod(x, a, p), p); } if (b != 0) { y2 = addmod(y2, b, p); } uint y_ = 0; if (p % 4 == 3) { y_ = ECCMath.expmod(y2, (p + 1) / 4, p); } else { // return; //TODO general algo or other fact methods here revert(); } uint cmp = yBit ^ y_ & 1; P[0] = x; P[1] = (cmp == 0) ? y_ : p - y_; return P; } function toAffine(uint[3] P) public view returns (uint[2] Q) { uint p = pp; ECCMath.toZ1(P, p); Q[0] = P[0]; Q[1] = P[1]; return Q; } }
P, 3P, 5P, 7P, 9P, 11P, 13P, 15P
uint[3][8] memory PREC;
5,390,561
[ 1, 52, 16, 890, 52, 16, 1381, 52, 16, 2371, 52, 16, 2468, 52, 16, 4648, 52, 16, 5958, 52, 16, 4711, 52, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 63, 23, 6362, 28, 65, 3778, 7071, 39, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/math/Math.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import 'openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; import 'openzeppelin-solidity/contracts/lifecycle/Destructible.sol'; import './libraries/strings.sol'; import './libraries/Array256Lib.sol'; import './BadgesLedger.sol'; /** * @title Mecenas * The main mecenas contract. Here is all the main logic to register * content creators and be able to support then via prepaid monthly * subscriptions. There is a percent fee + fixed fee per every subs * that goes to the contract owner to support development. Content * creators can withdraw their wage monthly. */ contract Mecenas is Ownable, Pausable, Destructible { using SafeMath for uint256; using Math for uint256; using Array256Lib for uint256[]; using strings for *; address public owner; uint256 public ownerBalance; BadgesLedger public badgesLedger; uint public feePercent; uint public fixedFee; struct PriceTierSuggestion { uint256 price; string title; string description; } struct MecenasMessage { bytes32 mecenasNick; address mecenasAddress; address contentCreatorAddress; string message; uint subscriptions; uint priceTier; } struct MecenasSupport { bytes32 nickname; address[] supportsContentCreators; } struct ContentCreator { bytes32 nickname; string description; uint256 creationTimestamp; uint256 subscriptionIndex; uint256 payday; uint256 balance; string ipfsAvatar; address[] mecenasAddresses; mapping (uint => uint256[]) mecenasSubscriptions; } struct Badge { uint256 tokenId; address contentCreatorAddress; } mapping (address => PriceTierSuggestion[3]) public suggestPriceTiers; mapping (address => MecenasMessage[]) public messageInbox; mapping (address => ContentCreator) public contentCreators; mapping (address => MecenasSupport) public mecenas; mapping (address => Badge[]) public mecenasBadges; mapping (bytes32 => address) public contentCreatorAddresses; /** * @dev Emits a new subscription message, from the mecenas to the content creator. * It can be showed in the main website or integrated into a streaming platform, * to show in live and see the content creator reaction. * * An integration with Twitch could be possible. */ event newSubscriptionMessage(address contentCreatorAddress, bytes32 mecenasNickname, string mecenasMessage); /** * Emits a new content creator. This can be consumed in the webapp to show latest content creators. */ event newContentCreator(address contentCreatorAddress, bytes32 nickname, string ipfsAvatar); /** * @dev Initialize the contract, sets an owner, a default feePercent and fixedFee. */ constructor() public { owner = msg.sender; feePercent = 1; fixedFee = 0.0006 ether; } /** @dev Set the badges ledger contract address * @param badgesLedgerAddress the Badges ledger deployed address */ function setBadgesLedgerContract(address badgesLedgerAddress) public onlyOwner { badgesLedger = BadgesLedger(badgesLedgerAddress); } /** * @dev Modifier to throw when msg.value is less than contract owner fee; */ modifier minimumAmount { require(msg.value > getMinimumAmount()); _; } /** * @dev Calculate and returns the minimum amount possible to surpass owner fees. * @return uint The minimum possible amount to surpass fees. */ function getMinimumAmount() public view returns(uint) { return fixedFee.add(fixedFee.mul(feePercent).div(100)); } /** * @dev Function that returns true if first argument is greater than minimum owner fee. * @param amount Test if amount is greater than minimum amount. * @return boolean */ function greaterThanMinimumAmount(uint amount) public view returns (bool) { return amount > getMinimumAmount(); } /** Owner functions **/ /** * @dev Set percent fee per content creator subscription. * @param newFee The new percent fee to be set */ function setPercentFee(uint256 newFee) public onlyOwner { feePercent = newFee; } /** * @dev Set fixed fee per content creator subscription. * @param newFee The new fixed fee to be set. */ function setFixedFee(uint256 newFee) public onlyOwner { fixedFee = newFee; } /** * @dev Pay the fee to the contract owner. Returns the remain amount to support the content creator. * @return uint256 Returns the remaining amount after fees. */ function payFee() private returns(uint256) { require(msg.value > getMinimumAmount()); uint256 currentAmount = msg.value; uint256 fee = fixedFee.add(currentAmount.mul(feePercent).div(100)); uint256 amountAfterFee = currentAmount - fee; require(amountAfterFee > 0); ownerBalance = ownerBalance + fee; return amountAfterFee; } /** @dev Withdraw owner fees, only callable by owner. */ function withdrawFees() public onlyOwner { // Remember to substract the pending withdraw before // sending to prevent re-entrancy attacks uint256 transferAmount = ownerBalance; ownerBalance -= transferAmount; msg.sender.transfer(transferAmount); } /** * Content creator functions */ /** @dev Get content creator tiers length, to be able to iterate it later. * @param contentCreatorAddress The content creator address. * @return The length of the array. */ function getTiersLength(address contentCreatorAddress) public view returns (uint) { return suggestPriceTiers[contentCreatorAddress].length; } /** @dev Get content creator tier content, by index. * @param contentCreatorAddress The content creator address. * @param index The index of the array. * @return title The title of the tier. * @return description The description of the tier. * @return price The price of the tier. */ function getTier(address contentCreatorAddress, uint index) public view returns ( string title, string description, uint price ) { PriceTierSuggestion memory tier = suggestPriceTiers[contentCreatorAddress][index]; title = tier.title; description = tier.description; price = tier.price; } /** @dev Content creator getter * @param addressInput The content creator address. * @return nickname The content creator name. * @return description Content creator description. * @return creationTimestamp Creation timestamp * @return payday Next content creator payday date * @return balance Current content creator balance * @return ipfsAvatar Current content creator Avatar IPFS hash * @return totalMecenas The number of subscriptions * @return contentCreatorAddress Address * @return wage The next wage value. */ function getContentCreator(address addressInput) public view returns ( bytes32 nickname, string description, uint256 creationTimestamp, uint256 payday, uint256 balance, string ipfsAvatar, uint256 totalMecenas, address contentCreatorAddress, uint256 wage ) { ContentCreator memory contentCreator = contentCreators[addressInput]; nickname = contentCreator.nickname; description = contentCreator.description; creationTimestamp = contentCreator.creationTimestamp; payday = contentCreator.payday; balance = contentCreator.balance; ipfsAvatar = contentCreator.ipfsAvatar; totalMecenas = contentCreator.mecenasAddresses.length; contentCreatorAddress = addressInput; wage = calculateNextWage(addressInput); } /** @dev Content creator getter * @param nickname The content creator nickname. * @return contentCreatorAddress address of content creator. */ function getContentCreatorAddress(bytes32 nickname) public view returns ( address contentCreatorAddress ) { contentCreatorAddress = contentCreatorAddresses[nickname]; } /** @dev Content creator getter * @param nick The content creator nickname. * @return nickname The content creator name. * @return description Content creator description. * @return creationTimestamp Creation timestamp * @return payday Next content creator payday date * @return balance Current content creator balance * @return ipfsAvatar Current content creator Avatar IPFS hash * @return totalMecenas The number of subscriptions * @return contentCreatorAddress Address * @return wage The next wage value. */ function getContentCreatorByNickname(bytes32 nick) public view returns ( bytes32 nickname, string description, uint256 creationTimestamp, uint256 payday, uint256 balance, string ipfsAvatar, uint256 totalMecenas, address contentCreatorAddress, uint256 wage ) { contentCreatorAddress = getContentCreatorAddress(nick); require(contentCreatorAddress != address(0)); ContentCreator memory contentCreator = contentCreators[contentCreatorAddress]; nickname = contentCreator.nickname; description = contentCreator.description; creationTimestamp = contentCreator.creationTimestamp; payday = contentCreator.payday; balance = contentCreator.balance; ipfsAvatar = contentCreator.ipfsAvatar; totalMecenas = contentCreator.mecenasAddresses.length; wage = calculateNextWage(contentCreatorAddress); } /** * @dev Sets the default price tiers to the current msg.sender */ function setDefaultPriceTiers() private { // Default tiers PriceTierSuggestion memory tierSilver = PriceTierSuggestion({ title: "Silver", description: "You will receive a Silver badge token in compensation, ocassional extra content like making-off videos or photos. And a lot of love.", price: getMinimumAmount() + 0.01 ether }); PriceTierSuggestion memory tierGold = PriceTierSuggestion({ title: "Gold", description: "You will receive a Gold badge token in compensation, extra video content and audio commentary of new and old videos. And a lot of love.", price: getMinimumAmount() + 0.02 ether }); PriceTierSuggestion memory tierPlatinum = PriceTierSuggestion({ title: "Platinum", description: "You will receive a Gold badge token in compensation, all of above and access to an exclusive forum, where i will reply to any question you want to ask to me. And a lot of love.", price: getMinimumAmount() + 0.05 ether }); suggestPriceTiers[msg.sender][0] = tierSilver; suggestPriceTiers[msg.sender][1] = tierGold; suggestPriceTiers[msg.sender][2] = tierPlatinum; } /** * @dev Gets the Mecenas Badge name for adding it to the Token URI * @param amount uint256 with the amount. * @param priceTiers The tiers of the content creator. */ function getSubscriberLevel(uint256 amount, PriceTierSuggestion[3] priceTiers) private pure returns (string){ bool levelFound = false; uint priceTierIndex = 0; uint currentLevel = 0; for(uint counter = 0; counter < 3; counter++){ if(amount > uint(priceTiers[counter].price)) { if (uint(priceTiers[counter].price) > currentLevel) { currentLevel = priceTiers[counter].price; priceTierIndex = counter; if (levelFound == false) { levelFound = true; } } } } if (levelFound == false) { return "Subscriber"; } return priceTiers[priceTierIndex].title; } /** @dev Content creator getter * @param nickname The content creator name. * @param description Content creator description. * @param ipfsAvatar Current content creator Avatar IPFS hash */ function contentCreatorFactory(bytes32 nickname, string description, string ipfsAvatar) public whenNotPaused { ContentCreator storage contentCreator = contentCreators[msg.sender]; // At least nickname must be greater than zero chars, be unique, and content creator must not exists require(nickname.length > 0 && contentCreatorAddresses[nickname] == address(0) && contentCreator.payday == 0); // Initialize a new content creator contentCreatorAddresses[nickname] = msg.sender; contentCreator.nickname = nickname; contentCreator.description = description; contentCreator.creationTimestamp = now; contentCreator.payday = now + 30 days; contentCreator.balance = 0; contentCreator.ipfsAvatar = ipfsAvatar; contentCreator.subscriptionIndex = 1; setDefaultPriceTiers(); // Emit content creator event emit newContentCreator(msg.sender, nickname, ipfsAvatar); } /** * @dev Change the content creator address, only allowed by content creator itself. * @param newAddress The new address to be set. */ function changeContentCreatorAddress(address newAddress) public whenNotPaused { ContentCreator memory current = contentCreators[msg.sender]; require(current.payday > 0); delete contentCreators[msg.sender]; delete contentCreatorAddresses[current.nickname]; contentCreators[newAddress] = current; contentCreatorAddresses[current.nickname] = newAddress; } /** * @dev Change the content creator avatar, only allowed by content creator itself. * @param avatarHash The new avatar IPFS hash to be set. */ function changeAvatar(string avatarHash) public whenNotPaused { ContentCreator storage current = contentCreators[msg.sender]; require(current.payday > 0); current.ipfsAvatar = avatarHash; } /** * @dev Change the content creator tier, by index, only allowed by content creator itself. * @param tierIndex The tier index to change. * @param title The new title name to be set. * @param description The new description to be set. * @param price The new price to be set. */ function changeContentCreatorTiers(uint tierIndex, string title, string description, uint256 price) public whenNotPaused { ContentCreator storage current = contentCreators[msg.sender]; // Check if content creator is initialized, price is greater than minimum amount and string params are not empty. require(current.payday > 0 && price > getMinimumAmount() && bytes(title).length > 0 && bytes(description).length > 0); // Replace value in global map variable suggestPriceTiers[msg.sender][tierIndex] = PriceTierSuggestion({ title: title, description: description, price: price }); } /** * @dev Change the content creator description, only allowed by content creator itself. * @param description The new description to be set. */ function changeDescription(string description) public whenNotPaused { ContentCreator storage current = contentCreators[msg.sender]; require(current.payday > 0); current.description = description; } /** * @dev Calculate next content creator wage. * @param contentCreatorAddress Content creator address * @return uint with the next content creator wage. */ function calculateNextWage(address contentCreatorAddress) public view returns (uint256){ ContentCreator storage contentCreator = contentCreators[contentCreatorAddress]; return contentCreator.mecenasSubscriptions[contentCreator.subscriptionIndex].sumElements(); } /** * @dev Allow content creator to withdraw once the payload date is greater or equal than today. If contract * is paused, this function is still reachable for content creators. */ function monthlyWithdraw() public { ContentCreator storage current = contentCreators[msg.sender]; uint nextWage = current.mecenasSubscriptions[current.subscriptionIndex].sumElements(); // Allow withdraw only after payday require(now >= current.payday && current.balance > 0); // If the current balance is less than the theorical monthly withdraw, withdraw that lower amount. uint transferAmount = current.balance.min256(nextWage); // Remember to lock the withdraw function until next month current.payday = current.payday + 30 days; // Point to the next subscription index current.subscriptionIndex = current.subscriptionIndex + 1; // Remember to substract the pending withdraw before // sending to prevent re-entrancy attacks current.balance = current.balance - transferAmount; msg.sender.transfer(transferAmount); } /** Mecenas functions **/ /** * @dev Emit a Mecenas Message event to be consumed in a stream or website. Show the support from the mecenas to the content creator. * @param mecenasNickname Mecenas nickname. * @param contentCreatorAddress Content creator address subscription. * @param message Mecenas message. * @param subscriptions Number of months subbed. * @param priceTier The subscription price per month. */ function broadcastNewSubscription(bytes32 mecenasNickname, address contentCreatorAddress, string message, uint256 subscriptions, uint256 priceTier) private { MecenasMessage memory newSubMessage = MecenasMessage({ mecenasNick: mecenasNickname, mecenasAddress: msg.sender, contentCreatorAddress: contentCreatorAddress, message: message, subscriptions: subscriptions, priceTier: priceTier }); // Save message into storage messageInbox[contentCreatorAddress].push(newSubMessage); // Send a new subscription event emit newSubscriptionMessage(newSubMessage.contentCreatorAddress, newSubMessage.mecenasNick, newSubMessage.message); } /** * @dev Support a determined content creator, via a prepaid monthly subscription. * You can set any price, regarding the suggested price tiers, and add a support message to the content creator. * @param mecenasNickname Mecenas nickname. * @param contentCreatorAddress Content creator address subscription. * @param message Mecenas message. * @param subscriptions Number of months subbed. */ function supportContentCreator(address contentCreatorAddress, uint256 subscriptions, string message, bytes32 mecenasNickname) public payable whenNotPaused{ require(contentCreatorAddress != address(0) && msg.value > 0); // Calculate fee and sum to contract owner balance uint256 amountAfterFees = payFee(); // Calculate price per month subscription (totalAmount / months = priceTier) uint256 priceTier = amountAfterFees.div(subscriptions); ContentCreator storage contentCreator = contentCreators[contentCreatorAddress]; require(contentCreator.subscriptionIndex >= 1); // Add the subscriptions to the content creator for (uint newSub = 0; newSub < subscriptions; newSub++) { contentCreator.mecenasSubscriptions[contentCreator.subscriptionIndex + newSub].push(priceTier); contentCreator.balance = contentCreator.balance + priceTier; } // Add the mecenas address to the content creator contentCreator.mecenasAddresses.push(msg.sender); // Save mecenas into global variable mecenas[msg.sender].nickname = mecenasNickname; mecenas[msg.sender].supportsContentCreators.push(contentCreatorAddress); // Mint SubscriptionBadge to Mecenas uint tokenId = badgesLedger.totalSupply() + 1; string memory subscriptionLevel = getSubscriberLevel(priceTier, suggestPriceTiers[contentCreatorAddress]); // Token uri contains "level" string string memory tokenUri = subscriptionLevel; badgesLedger.mintSubscriptionBadge(msg.sender, tokenId, tokenUri); // Save token into separate map, that contains tokenId and contentCreator address, mapped by mecenas address. Badge[] storage mecenasTokens = mecenasBadges[msg.sender]; mecenasTokens.push(Badge({tokenId: tokenId, contentCreatorAddress: contentCreatorAddress})); // Send message to the content creator inbox and emit event broadcastNewSubscription(mecenasNickname, contentCreatorAddress, message, subscriptions, priceTier); } }
* @dev Get content creator tier content, by index. @param contentCreatorAddress The content creator address. @param index The index of the array. @return title The title of the tier. @return description The description of the tier. @return price The price of the tier./
function getTier(address contentCreatorAddress, uint index) public view returns ( string title, string description, uint price ) { PriceTierSuggestion memory tier = suggestPriceTiers[contentCreatorAddress][index]; title = tier.title; description = tier.description; price = tier.price; }
7,284,489
[ 1, 967, 913, 11784, 17742, 913, 16, 635, 770, 18, 225, 913, 10636, 1887, 1021, 913, 11784, 1758, 18, 225, 770, 1021, 770, 434, 326, 526, 18, 327, 2077, 1021, 2077, 434, 326, 17742, 18, 327, 2477, 1021, 2477, 434, 326, 17742, 18, 327, 6205, 1021, 6205, 434, 326, 17742, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 3181, 2453, 12, 2867, 913, 10636, 1887, 16, 2254, 770, 13, 1071, 1476, 1135, 261, 203, 565, 533, 2077, 16, 203, 565, 533, 2477, 16, 203, 565, 2254, 6205, 203, 225, 262, 288, 203, 565, 20137, 15671, 31561, 3778, 17742, 273, 19816, 5147, 56, 20778, 63, 1745, 10636, 1887, 6362, 1615, 15533, 203, 565, 2077, 273, 17742, 18, 2649, 31, 203, 565, 2477, 273, 17742, 18, 3384, 31, 203, 565, 6205, 273, 17742, 18, 8694, 31, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x1ab9570281c7b3ceec24524d4fd7d94a8fe1a8c8 //Contract name: NaorisToken //Balance: 0 Ether //Verification Date: 6/11/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity 0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; constructor(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public { require(_releaseTime > uint64(block.timestamp)); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(uint64(block.timestamp) >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } contract ReferralDiscountToken is StandardToken, Owned { /// Store the referrers by the referred addresses mapping(address => address) referrerOf; address[] ownersIndex; // Emitted when an investor declares his referrer event Referral(address indexed referred, address indexed referrer); /// Compute the earned discount, topped at 60% function referralDiscountPercentage(address _owner) public view returns (uint256 percent) { uint256 total = 0; /// get one time discount for having been referred if(referrerOf[_owner] != address(0)) { total = total.add(10); } /// get a 10% discount for each one referred for(uint256 i = 0; i < ownersIndex.length; i++) { if(referrerOf[ownersIndex[i]] == _owner) { total = total.add(10); // if(total >= 60) break; } } return total; } // /** // * Activate referral discounts by declaring one's own referrer // * @param _referrer can't be self // * @param _referrer must own tokens at the time of the call // * You must own tokens at the time of the call // */ // function setReferrer(address _referrer) public returns (bool success) { // require(_referrer != address(0)); // require(_referrer != address(msg.sender)); // require(balanceOf(msg.sender) > 0); // require(balanceOf(_referrer) > 0); // assert(referrerOf[msg.sender] == address(0)); // ownersIndex.push(msg.sender); // referrerOf[msg.sender] = _referrer; // Referral(msg.sender, _referrer); // return true; // } /** * Activate referral discounts by declaring one's own referrer * @param _referrer the investor who brought another * @param _referred the investor who was brought by another * @dev _referrer and _referred must own tokens at the time of the call */ function setReferrer(address _referred, address _referrer) onlyOwner public returns (bool success) { require(_referrer != address(0)); require(_referrer != address(_referred)); // require(balanceOf(_referred) > 0); // require(balanceOf(_referrer) > 0); require(referrerOf[_referred] == address(0)); ownersIndex.push(_referred); referrerOf[_referred] = _referrer; emit Referral(_referred, _referrer); return true; } } contract NaorisToken is ReferralDiscountToken { string public constant name = "NaorisToken"; string public constant symbol = "NAO"; uint256 public constant decimals = 18; /// The owner of this address will manage the sale process. address public saleTeamAddress; /// The owner of this address will manage the referal and airdrop campaigns. address public referalAirdropsTokensAddress; /// The owner of this address is the Naoris Reserve fund. address public reserveFundAddress; /// The owner of this address is the Naoris Think Tank fund. address public thinkTankFundAddress; /// This address keeps the locked board bonus until 1st of May 2019 address public lockedBoardBonusAddress; /// This is the address of the timelock contract for the locked Board Bonus tokens address public treasuryTimelockAddress; /// After this flag is changed to 'true' no more tokens can be created bool public tokenSaleClosed = false; // seconds since 01.01.1970 to 1st of May 2019 (both 00:00:00 o'clock UTC) uint64 date01May2019 = 1556668800; /// Maximum tokens to be allocated. uint256 public constant TOKENS_HARD_CAP = 400000000 * 10 ** decimals; /// Maximum tokens to be sold. uint256 public constant TOKENS_SALE_HARD_CAP = 300000000 * 10 ** decimals; /// Tokens to be allocated to the Referal tokens fund. uint256 public constant REFERRAL_TOKENS = 10000000 * 10 ** decimals; /// Tokens to be allocated to the Airdrop tokens fund. uint256 public constant AIRDROP_TOKENS = 10000000 * 10 ** decimals; /// Tokens to be allocated to the Think Tank fund. uint256 public constant THINK_TANK_FUND_TOKENS = 40000000 * 10 ** decimals; /// Tokens to be allocated to the Naoris Team fund. uint256 public constant NAORIS_TEAM_TOKENS = 20000000 * 10 ** decimals; /// Tokens to be allocated to the locked Board Bonus. uint256 public constant LOCKED_BOARD_BONUS_TOKENS = 20000000 * 10 ** decimals; /// Only the sale team or the owner are allowed to execute modifier onlyTeam { assert(msg.sender == saleTeamAddress || msg.sender == owner); _; } /// Only allowed to execute while the sale is not yet closed modifier beforeEnd { assert(!tokenSaleClosed); _; } constructor(address _saleTeamAddress, address _referalAirdropsTokensAddress, address _reserveFundAddress, address _thinkTankFundAddress, address _lockedBoardBonusAddress) public { require(_saleTeamAddress != address(0)); require(_referalAirdropsTokensAddress != address(0)); require(_reserveFundAddress != address(0)); require(_thinkTankFundAddress != address(0)); require(_lockedBoardBonusAddress != address(0)); saleTeamAddress = _saleTeamAddress; referalAirdropsTokensAddress = _referalAirdropsTokensAddress; reserveFundAddress = _reserveFundAddress; thinkTankFundAddress = _thinkTankFundAddress; lockedBoardBonusAddress = _lockedBoardBonusAddress; /// The unsold sale tokens will be burnt when the sale is closed balances[saleTeamAddress] = TOKENS_SALE_HARD_CAP; totalSupply_ = TOKENS_SALE_HARD_CAP; emit Transfer(0x0, saleTeamAddress, TOKENS_SALE_HARD_CAP); /// The unspent referal/airdrop tokens will be sent back /// to the reserve fund when the sale is closed balances[referalAirdropsTokensAddress] = REFERRAL_TOKENS; totalSupply_ = totalSupply_.add(REFERRAL_TOKENS); emit Transfer(0x0, referalAirdropsTokensAddress, REFERRAL_TOKENS); balances[referalAirdropsTokensAddress] = balances[referalAirdropsTokensAddress].add(AIRDROP_TOKENS); totalSupply_ = totalSupply_.add(AIRDROP_TOKENS); emit Transfer(0x0, referalAirdropsTokensAddress, AIRDROP_TOKENS); } function close() public onlyTeam beforeEnd { /// burn the unsold sale tokens uint256 unsoldSaleTokens = balances[saleTeamAddress]; if(unsoldSaleTokens > 0) { balances[saleTeamAddress] = 0; totalSupply_ = totalSupply_.sub(unsoldSaleTokens); emit Transfer(saleTeamAddress, 0x0, unsoldSaleTokens); } /// transfer the unspent referal/airdrop tokens to the Reserve fund uint256 unspentReferalAirdropTokens = balances[referalAirdropsTokensAddress]; if(unspentReferalAirdropTokens > 0) { balances[referalAirdropsTokensAddress] = 0; balances[reserveFundAddress] = balances[reserveFundAddress].add(unspentReferalAirdropTokens); emit Transfer(referalAirdropsTokensAddress, reserveFundAddress, unspentReferalAirdropTokens); } /// 40% allocated to the Naoris Think Tank Fund balances[thinkTankFundAddress] = balances[thinkTankFundAddress].add(THINK_TANK_FUND_TOKENS); totalSupply_ = totalSupply_.add(THINK_TANK_FUND_TOKENS); emit Transfer(0x0, thinkTankFundAddress, THINK_TANK_FUND_TOKENS); /// 20% allocated to the Naoris Team and Advisors Fund balances[owner] = balances[owner].add(NAORIS_TEAM_TOKENS); totalSupply_ = totalSupply_.add(NAORIS_TEAM_TOKENS); emit Transfer(0x0, owner, NAORIS_TEAM_TOKENS); /// tokens of the Board Bonus locked until 1st of May 2019 TokenTimelock lockedTreasuryTokens = new TokenTimelock(this, lockedBoardBonusAddress, date01May2019); treasuryTimelockAddress = address(lockedTreasuryTokens); balances[treasuryTimelockAddress] = balances[treasuryTimelockAddress].add(LOCKED_BOARD_BONUS_TOKENS); totalSupply_ = totalSupply_.add(LOCKED_BOARD_BONUS_TOKENS); emit Transfer(0x0, treasuryTimelockAddress, LOCKED_BOARD_BONUS_TOKENS); require(totalSupply_ <= TOKENS_HARD_CAP); tokenSaleClosed = true; } function tokenDiscountPercentage(address _owner) public view returns (uint256 percent) { if(balanceOf(_owner) >= 1000000 * 10**decimals) { return 50; } else if(balanceOf(_owner) >= 500000 * 10**decimals) { return 30; } else if(balanceOf(_owner) >= 250000 * 10**decimals) { return 25; } else if(balanceOf(_owner) >= 100000 * 10**decimals) { return 20; } else if(balanceOf(_owner) >= 50000 * 10**decimals) { return 15; } else if(balanceOf(_owner) >= 10000 * 10**decimals) { return 10; } else if(balanceOf(_owner) >= 1000 * 10**decimals) { return 5; } else { return 0; } } function getTotalDiscount(address _owner) public view returns (uint256 percent) { uint256 total = 0; total += tokenDiscountPercentage(_owner); total += referralDiscountPercentage(_owner); return (total > 60) ? 60 : total; } /// @dev Trading limited - requires the token sale to have closed function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if(tokenSaleClosed) { return super.transferFrom(_from, _to, _value); } return false; } /// @dev Trading limited - requires the token sale to have closed function transfer(address _to, uint256 _value) public returns (bool) { if(tokenSaleClosed || msg.sender == referalAirdropsTokensAddress || msg.sender == saleTeamAddress) { return super.transfer(_to, _value); } return false; } }
* @title TokenTimelock @dev TokenTimelock is a token holder contract that will allow a beneficiary to extract the tokens after a given release time/ ERC20 basic token contract being held beneficiary of tokens after they are released timestamp when token release is enabled
contract TokenTimelock { using SafeERC20 for ERC20Basic; ERC20Basic public token; address public beneficiary; uint64 public releaseTime; constructor(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public { require(_releaseTime > uint64(block.timestamp)); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } function release() public { require(uint64(block.timestamp) >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } }
1,771,233
[ 1, 1345, 10178, 292, 975, 225, 3155, 10178, 292, 975, 353, 279, 1147, 10438, 6835, 716, 903, 1699, 279, 27641, 74, 14463, 814, 358, 2608, 326, 2430, 1839, 279, 864, 3992, 813, 19, 4232, 39, 3462, 5337, 1147, 6835, 3832, 15770, 27641, 74, 14463, 814, 434, 2430, 1839, 2898, 854, 15976, 2858, 1347, 1147, 3992, 353, 3696, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 10178, 292, 975, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 3462, 8252, 31, 203, 203, 565, 4232, 39, 3462, 8252, 1071, 1147, 31, 203, 203, 565, 1758, 1071, 27641, 74, 14463, 814, 31, 203, 203, 565, 2254, 1105, 1071, 3992, 950, 31, 203, 203, 565, 3885, 12, 654, 39, 3462, 8252, 389, 2316, 16, 1758, 389, 70, 4009, 74, 14463, 814, 16, 2254, 1105, 389, 9340, 950, 13, 1071, 288, 203, 3639, 2583, 24899, 9340, 950, 405, 2254, 1105, 12, 2629, 18, 5508, 10019, 203, 3639, 1147, 273, 389, 2316, 31, 203, 3639, 27641, 74, 14463, 814, 273, 389, 70, 4009, 74, 14463, 814, 31, 203, 3639, 3992, 950, 273, 389, 9340, 950, 31, 203, 565, 289, 203, 203, 565, 445, 3992, 1435, 1071, 288, 203, 3639, 2583, 12, 11890, 1105, 12, 2629, 18, 5508, 13, 1545, 3992, 950, 1769, 203, 203, 3639, 2254, 5034, 3844, 273, 1147, 18, 12296, 951, 12, 2211, 1769, 203, 3639, 2583, 12, 8949, 405, 374, 1769, 203, 203, 3639, 1147, 18, 4626, 5912, 12, 70, 4009, 74, 14463, 814, 16, 3844, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x924E2C9099B864923F6a66aC439FaBEac15957A6/sources/contracts/masterchef.sol
* @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of BEP20 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 {IBEP20-approve}./
contract BEP20 is Context, IBEP20, Ownable { 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; constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function getOwner() external override view returns (address) { return owner(); } function name() public override view returns (string memory) { return _name; } function symbol() public override view returns (string memory) { return _symbol; } function decimals() public override view returns (uint8) { return _decimals; } function totalSupply() public override view returns (uint256) { return _totalSupply; } function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom (address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance') ); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')); return true; } function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } function _transfer (address sender, address recipient, uint256 amount) internal { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve (address owner, address spender, uint256 amount) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance')); } }
3,757,497
[ 1, 13621, 434, 326, 288, 45, 5948, 52, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 5948, 52, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 9722, 52, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 9722, 52, 3462, 353, 1772, 16, 467, 5948, 52, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 13782, 1435, 3903, 3849, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 3410, 5621, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 3849, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 3849, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 3849, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 2 ]
pragma solidity 0.4.24; import "./ERCProxy.sol"; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. * @dev source https://github.com/zeppelinos/labs/blob/master/upgradeability_using_unstructured_storage/contracts/Proxy.sol */ contract Proxy is ERCProxy { // Storage position of the address of the current implementation bytes32 private constant typeIdPosition = keccak256("org.meridio.proxy.typeId"); /** * @dev Sets the proxyTypeId. Should be called from the Proxy constructor * @param _proxyTypeId uint representing Forwarding Proxy (id = 1) or Upgradeable Proxy (id = 2); */ function setProxyTypeId (uint256 _proxyTypeId) internal { require(_proxyTypeId == 1 || _proxyTypeId == 2, "Must be type 1 or 2"); bytes32 position = typeIdPosition; assembly { // solhint-disable-line sstore(position, _proxyTypeId) } } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function proxyType() public view returns (uint256 proxyTypeId) { bytes32 position = typeIdPosition; assembly { // solhint-disable-line proxyTypeId := sload(position) } } /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () public payable { address _impl = implementation(); require(_impl != address(0)); assembly { // solhint-disable-line let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
* @title Proxy @dev Gives the possibility to delegate any call to a foreign implementation./ Storage position of the address of the current implementation
contract Proxy is ERCProxy { bytes32 private constant typeIdPosition = keccak256("org.meridio.proxy.typeId"); function setProxyTypeId (uint256 _proxyTypeId) internal { require(_proxyTypeId == 1 || _proxyTypeId == 2, "Must be type 1 or 2"); bytes32 position = typeIdPosition; sstore(position, _proxyTypeId) } }
1,047,664
[ 1, 3886, 225, 611, 3606, 326, 25547, 358, 7152, 1281, 745, 358, 279, 5523, 4471, 18, 19, 5235, 1754, 434, 326, 1758, 434, 326, 783, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7659, 353, 4232, 39, 3886, 288, 203, 203, 565, 1731, 1578, 3238, 5381, 24361, 2555, 273, 417, 24410, 581, 5034, 2932, 3341, 18, 6592, 350, 1594, 18, 5656, 18, 723, 548, 8863, 203, 203, 565, 445, 444, 3886, 11731, 261, 11890, 5034, 389, 5656, 11731, 13, 2713, 288, 203, 3639, 2583, 24899, 5656, 11731, 422, 404, 747, 389, 5656, 11731, 422, 576, 16, 315, 10136, 506, 618, 404, 578, 576, 8863, 203, 3639, 1731, 1578, 1754, 273, 24361, 2555, 31, 203, 5411, 272, 2233, 12, 3276, 16, 389, 5656, 11731, 13, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-11-29 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IBaseFee interface IBaseFee { function isCurrentBaseFeeAcceptable() external view returns (bool); } // Part: IConvexDeposit interface IConvexDeposit { // deposit into convex, receive a tokenized deposit. parameter to stake immediately (we always do this). function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); // burn a tokenized deposit (Convex deposit tokens) to receive curve lp tokens back function withdraw(uint256 _pid, uint256 _amount) external returns (bool); // give us info about a pool based on its pid function poolInfo(uint256) external view returns ( address, address, address, address, address, bool ); } // Part: IConvexRewards interface IConvexRewards { // strategy's staked balance in the synthetix staking contract function balanceOf(address account) external view returns (uint256); // read how much claimable CRV a strategy has function earned(address account) external view returns (uint256); // stake a convex tokenized deposit function stake(uint256 _amount) external returns (bool); // withdraw to a convex tokenized deposit, probably never need to use this function withdraw(uint256 _amount, bool _claim) external returns (bool); // withdraw directly to curve LP token, this is what we primarily use function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool); // claim rewards, with an option to claim extra rewards or not function getReward(address _account, bool _claimExtras) external returns (bool); // check if we have rewards on a pool function extraRewardsLength() external view returns (uint256); // if we have rewards, see what the address is function extraRewards(uint256 _reward) external view returns (address); // read our rewards token function rewardToken() external view returns (address); // check our reward period finish function periodFinish() external view returns (uint256); } // Part: ICurveFi interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // EURt uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // Compound, sAave uint256[2] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // Iron Bank, Aave uint256[3] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3Crv Metapools address pool, uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // Y and yBUSD uint256[4] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3pool uint256[3] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // sUSD uint256[4] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(uint256) external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); // EURt function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3Crv Metapools function calc_token_amount( address _pool, uint256[4] calldata _amounts, bool _is_deposit ) external view returns (uint256); // sUSD, Y pool, etc function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3pool, Iron Bank, etc function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit) external view returns (uint256); function calc_withdraw_one_coin(uint256 amount, int128 i) external view returns (uint256); } // Part: IUniV3 interface IUniV3 { struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); } // Part: IUniswapV2Router01 interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: StrategyConvexBase abstract contract StrategyConvexBase is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // these should stay the same across different wants. // convex stuff address public constant depositContract = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; // this is the deposit contract that all pools use, aka booster IConvexRewards public rewardsContract; // This is unique to each curve pool uint256 public pid; // this is unique to each pool // keepCRV stuff uint256 public keepCRV; // the percentage of CRV we re-lock for boost (in basis points) address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter, we send some extra CRV here uint256 internal constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in basis points // Swap stuff address internal constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV and CVX liquidity there IERC20 internal constant crv = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 internal constant convexToken = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); IERC20 internal constant weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // keeper stuff uint256 public harvestProfitMin; // minimum size in USDT that we want to harvest uint256 public harvestProfitMax; // maximum size in USDT that we want to harvest bool internal forceHarvestTriggerOnce; // only set this to true when we want to trigger our keepers to harvest for us string internal stratName; // we use this to be able to adjust our strategy's name // convex-specific variables bool public claimRewards; // boolean if we should always claim rewards when withdrawing, usually withdrawAndUnwrap (generally this should be false) /* ========== CONSTRUCTOR ========== */ constructor(address _vault) public BaseStrategy(_vault) {} /* ========== VIEWS ========== */ function name() external view override returns (string memory) { return stratName; } function stakedBalance() public view returns (uint256) { // how much want we have staked in Convex return rewardsContract.balanceOf(address(this)); } function balanceOfWant() public view returns (uint256) { // balance of want sitting in our strategy return want.balanceOf(address(this)); } function claimableBalance() public view returns (uint256) { // how much CRV we can claim from the staking contract return rewardsContract.earned(address(this)); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(stakedBalance()); } /* ========== CONSTANT FUNCTIONS ========== */ // these should stay the same across different wants. function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } // Send all of our Curve pool tokens to be deposited uint256 _toInvest = balanceOfWant(); // deposit into convex and stake immediately but only if we have something to invest if (_toInvest > 0) { IConvexDeposit(depositContract).deposit(pid, _toInvest, true); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _wantBal = balanceOfWant(); if (_amountNeeded > _wantBal) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdrawAndUnwrap( Math.min(_stakedBal, _amountNeeded.sub(_wantBal)), claimRewards ); } uint256 _withdrawnBal = balanceOfWant(); _liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal); _loss = _amountNeeded.sub(_liquidatedAmount); } else { // we have enough balance to cover the liquidation available return (_amountNeeded, 0); } } // fire sale, get rid of it all! function liquidateAllPositions() internal override returns (uint256) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { // don't bother withdrawing zero rewardsContract.withdrawAndUnwrap(_stakedBal, claimRewards); } return balanceOfWant(); } // in case we need to exit into the convex deposit token, this will allow us to do that // make sure to check claimRewards before this step if needed // plan to have gov sweep convex deposit tokens from strategy after this function withdrawToConvexDepositTokens() external onlyAuthorized { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdraw(_stakedBal, claimRewards); } } // we don't want for these tokens to be swept out. We allow gov to sweep out cvx vault tokens; we would only be holding these if things were really, really rekt. function protectedTokens() internal view override returns (address[] memory) {} /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%. function setKeepCRV(uint256 _keepCRV) external onlyAuthorized { require(_keepCRV <= 10_000); keepCRV = _keepCRV; } // We usually don't need to claim rewards on withdrawals, but might change our mind for migrations etc function setClaimRewards(bool _claimRewards) external onlyAuthorized { claimRewards = _claimRewards; } // This determines when we tell our keepers to start allowing harvests based on profit, and when to sell no matter what. this is how much in USDT we need to make. remember, 6 decimals! function setHarvestProfitNeeded( uint256 _harvestProfitMin, uint256 _harvestProfitMax ) external onlyAuthorized { harvestProfitMin = _harvestProfitMin; harvestProfitMax = _harvestProfitMax; } // This allows us to manually harvest with our keeper as needed function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce) external onlyAuthorized { forceHarvestTriggerOnce = _forceHarvestTriggerOnce; } } // File: StrategyConvexD3Pool.sol contract StrategyConvexD3pool is StrategyConvexBase { /* ========== STATE VARIABLES ========== */ // these will likely change across different wants. // Curve stuff ICurveFi public constant curve = ICurveFi(0xBaaa1F5DbA42C3389bDbc2c9D2dE134F5cD0Dc89); // This is our pool specific to this vault. bool public checkEarmark; // this determines if we should check if we need to earmark rewards before harvesting // we use these to deposit to our curve pool uint256 internal optimal; // this is the optimal token to deposit back to our curve pool. 0 FEI, 1 FRAX IERC20 internal constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); address internal constant uniswapv3 = address(0xE592427A0AEce92De3Edee1F18E0157C05861564); address public targetStable; IERC20 internal constant fei = IERC20(0x956F47F50A910163D8BF957Cf5846D573E7f87CA); IERC20 internal constant frax = IERC20(0x853d955aCEf822Db058eb8505911ED77F175b99e); uint24 public uniCrvFee; // this is equal to 1%, can change this later if a different path becomes more optimal uint24 public uniUsdcFee; // this is equal to 0.05%, can change this later if a different path becomes more optimal uint24 public uniStableFee; // this is equal to 0.05%, can change this later if a different path becomes more optimal /* ========== CONSTRUCTOR ========== */ constructor( address _vault, uint256 _pid, string memory _name ) public StrategyConvexBase(_vault) { // want = Curve LP want.approve(address(depositContract), type(uint256).max); convexToken.approve(sushiswap, type(uint256).max); crv.approve(uniswapv3, type(uint256).max); weth.approve(uniswapv3, type(uint256).max); // setup our rewards contract pid = _pid; // this is the pool ID on convex, we use this to determine what the reweardsContract address is (address lptoken, , , address _rewardsContract, , ) = IConvexDeposit(depositContract).poolInfo(_pid); // set up our rewardsContract rewardsContract = IConvexRewards(_rewardsContract); // check that our LP token based on our pid matches our want require(address(lptoken) == address(want)); // set our strategy's name stratName = _name; // these are our approvals and path specific to this contract fei.approve(address(curve), type(uint256).max); frax.approve(address(curve), type(uint256).max); targetStable = address(fei); // set our uniswap pool fees uniCrvFee = 10000; uniUsdcFee = 500; uniStableFee = 500; } /* ========== VARIABLE FUNCTIONS ========== */ // these will likely change across different wants. function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // this claims our CRV, CVX, and any extra tokens like SNX or ANKR. no harm leaving this true even if no extra rewards currently. rewardsContract.getReward(address(this), true); uint256 crvBalance = crv.balanceOf(address(this)); uint256 convexBalance = convexToken.balanceOf(address(this)); uint256 _sendToVoter = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR); if (_sendToVoter > 0) { crv.safeTransfer(voter, _sendToVoter); } uint256 crvRemainder = crvBalance.sub(_sendToVoter); if (crvRemainder > 0 || convexBalance > 0) { _sellCrvAndCvx(crvRemainder, convexBalance); } // deposit our balance to Curve if we have any if (optimal == 0) { uint256 _feiBalance = fei.balanceOf(address(this)); if (_feiBalance > 0) { curve.add_liquidity([0, _feiBalance, 0], 0); } } else { uint256 _fraxBalance = frax.balanceOf(address(this)); if (_fraxBalance > 0) { curve.add_liquidity([_fraxBalance, 0, 0], 0); } } // debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio if (_debtOutstanding > 0) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdrawAndUnwrap( Math.min(_stakedBal, _debtOutstanding), claimRewards ); } uint256 _withdrawnBal = balanceOfWant(); _debtPayment = Math.min(_debtOutstanding, _withdrawnBal); } // serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately uint256 assets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; // if assets are greater than debt, things are working great! if (assets > debt) { _profit = assets.sub(debt); uint256 _wantBal = balanceOfWant(); if (_profit.add(_debtPayment) > _wantBal) { // this should only be hit following donations to strategy liquidateAllPositions(); } } // if assets are less than debt, we are in trouble else { _loss = debt.sub(assets); } // we're done harvesting, so reset our trigger if we used it forceHarvestTriggerOnce = false; } // Sells our CRV -> WETH on UniV3 and CVX -> WETH on Sushi, then WETH -> stables together on UniV3 function _sellCrvAndCvx(uint256 _crvAmount, uint256 _convexAmount) internal { address[] memory convexTokenPath = new address[](2); convexTokenPath[0] = address(convexToken); convexTokenPath[1] = address(weth); if (_convexAmount > 0) { IUniswapV2Router02(sushiswap).swapExactTokensForTokens( _convexAmount, uint256(0), convexTokenPath, address(this), block.timestamp ); } if (_crvAmount > 0) { IUniV3(uniswapv3).exactInput( IUniV3.ExactInputParams( abi.encodePacked( address(crv), uint24(uniCrvFee), address(weth) ), address(this), block.timestamp, _crvAmount, uint256(1) ) ); } uint256 _wethBalance = weth.balanceOf(address(this)); if (_wethBalance > 0) { IUniV3(uniswapv3).exactInput( IUniV3.ExactInputParams( abi.encodePacked( address(weth), uint24(uniUsdcFee), address(usdc), uint24(uniStableFee), address(targetStable) ), address(this), block.timestamp, _wethBalance, uint256(1) ) ); } } // migrate our want token to a new strategy if needed, make sure to check claimRewards first // also send over any CRV or CVX that is claimed; for migrations we definitely want to claim function prepareMigration(address _newStrategy) internal override { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdrawAndUnwrap(_stakedBal, claimRewards); } crv.safeTransfer(_newStrategy, crv.balanceOf(address(this))); convexToken.safeTransfer( _newStrategy, convexToken.balanceOf(address(this)) ); } /* ========== KEEP3RS ========== */ // use this to determine when to harvest function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { // only check if we need to earmark on vaults we know are problematic if (checkEarmark) { // don't harvest if we need to earmark convex rewards if (needsEarmarkReward()) { return false; } } // harvest if we have a profit to claim at our upper limit without considering gas price uint256 claimableProfit = claimableProfitInUsdt(); if (claimableProfit > harvestProfitMax) { return true; } // check if the base fee gas price is higher than we allow. if it is, block harvests. if (!isBaseFeeAcceptable()) { return false; } // trigger if we want to manually harvest, but only if our gas price is acceptable if (forceHarvestTriggerOnce) { return true; } // harvest if we have a sufficient profit to claim, but only if our gas price is acceptable if (claimableProfit > harvestProfitMin) { return true; } // otherwise, we don't harvest return false; } // we will need to add rewards token here if we have them function claimableProfitInUsdt() internal view returns (uint256) { // calculations pulled directly from CVX's contract for minting CVX per CRV claimed uint256 totalCliffs = 1_000; uint256 maxSupply = 100 * 1_000_000 * 1e18; // 100mil uint256 reductionPerCliff = 100_000 * 1e18; // 100,000 uint256 supply = convexToken.totalSupply(); uint256 mintableCvx; uint256 cliff = supply.div(reductionPerCliff); uint256 _claimableBal = claimableBalance(); //mint if below total cliffs if (cliff < totalCliffs) { //for reduction% take inverse of current cliff uint256 reduction = totalCliffs.sub(cliff); //reduce mintableCvx = _claimableBal.mul(reduction).div(totalCliffs); //supply cap check uint256 amtTillMax = maxSupply.sub(supply); if (mintableCvx > amtTillMax) { mintableCvx = amtTillMax; } } address[] memory usd_path = new address[](3); usd_path[0] = address(crv); usd_path[1] = address(weth); usd_path[2] = address(usdc); uint256 crvValue; if (_claimableBal > 0) { uint256[] memory crvSwap = IUniswapV2Router02(sushiswap).getAmountsOut( _claimableBal, usd_path ); crvValue = crvSwap[crvSwap.length - 1]; } usd_path[0] = address(convexToken); uint256 cvxValue; if (mintableCvx > 0) { uint256[] memory cvxSwap = IUniswapV2Router02(sushiswap).getAmountsOut( mintableCvx, usd_path ); cvxValue = cvxSwap[cvxSwap.length - 1]; } return crvValue.add(cvxValue); } // convert our keeper's eth cost into want, we don't need this anymore since we don't use baseStrategy harvestTrigger function ethToWant(uint256 _ethAmount) public view override returns (uint256) { return _ethAmount; } // check if the current baseFee is below our external target function isBaseFeeAcceptable() internal view returns (bool) { return IBaseFee(0xb5e1CAcB567d98faaDB60a1fD4820720141f064F) .isCurrentBaseFeeAcceptable(); } // check if someone needs to earmark rewards on convex before keepers harvest again function needsEarmarkReward() public view returns (bool needsEarmark) { // check if there is any CRV we need to earmark uint256 crvExpiry = rewardsContract.periodFinish(); if (crvExpiry < block.timestamp) { return true; } } /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Set optimal token to sell harvested funds for depositing to Curve. // Default is FEI, but can be set to FRAX as needed by strategist or governance. function setOptimal(uint256 _optimal) external onlyAuthorized { if (_optimal == 0) { targetStable = address(fei); optimal = 0; } else if (_optimal == 1) { targetStable = address(frax); optimal = 1; } else { revert("incorrect token"); } } // determine whether we will check if our convex rewards need to be earmarked function setCheckEarmark(bool _checkEarmark) external onlyAuthorized { checkEarmark = _checkEarmark; } // set the fee pool we'd like to swap through for CRV on UniV3 (1% = 10_000) function setUniFees( uint24 _crvFee, uint24 _usdcFee, uint24 _stableFee ) external onlyAuthorized { uniCrvFee = _crvFee; uniUsdcFee = _usdcFee; uniStableFee = _stableFee; } }
========== CONSTRUCTOR ========== */ want = Curve LP setup our rewards contract set up our rewardsContract check that our LP token based on our pid matches our want set our strategy's name these are our approvals and path specific to this contract set our uniswap pool fees
) public StrategyConvexBase(_vault) { want.approve(address(depositContract), type(uint256).max); convexToken.approve(sushiswap, type(uint256).max); crv.approve(uniswapv3, type(uint256).max); weth.approve(uniswapv3, type(uint256).max); (address lptoken, , , address _rewardsContract, , ) = IConvexDeposit(depositContract).poolInfo(_pid); rewardsContract = IConvexRewards(_rewardsContract); require(address(lptoken) == address(want)); stratName = _name; fei.approve(address(curve), type(uint256).max); frax.approve(address(curve), type(uint256).max); targetStable = address(fei); uniCrvFee = 10000; uniUsdcFee = 500; uniStableFee = 500; }
10,719,622
[ 1, 1432, 631, 3492, 13915, 916, 422, 1432, 342, 2545, 273, 22901, 511, 52, 3875, 3134, 283, 6397, 6835, 444, 731, 3134, 283, 6397, 8924, 866, 716, 3134, 511, 52, 1147, 2511, 603, 3134, 4231, 1885, 3134, 2545, 444, 3134, 6252, 1807, 508, 4259, 854, 3134, 6617, 4524, 471, 589, 2923, 358, 333, 6835, 444, 3134, 640, 291, 91, 438, 2845, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 1071, 19736, 17467, 338, 2171, 24899, 26983, 13, 288, 203, 3639, 2545, 18, 12908, 537, 12, 2867, 12, 323, 1724, 8924, 3631, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 3639, 26213, 1345, 18, 12908, 537, 12, 87, 1218, 291, 91, 438, 16, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 3639, 4422, 90, 18, 12908, 537, 12, 318, 291, 91, 438, 90, 23, 16, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 3639, 341, 546, 18, 12908, 537, 12, 318, 291, 91, 438, 90, 23, 16, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 203, 3639, 261, 2867, 328, 337, 969, 16, 269, 269, 1758, 389, 266, 6397, 8924, 16, 269, 262, 273, 203, 5411, 467, 17467, 338, 758, 1724, 12, 323, 1724, 8924, 2934, 6011, 966, 24899, 6610, 1769, 203, 203, 3639, 283, 6397, 8924, 273, 467, 17467, 338, 17631, 14727, 24899, 266, 6397, 8924, 1769, 203, 203, 3639, 2583, 12, 2867, 12, 80, 337, 969, 13, 422, 1758, 12, 17369, 10019, 203, 203, 3639, 609, 270, 461, 273, 389, 529, 31, 203, 203, 3639, 1656, 77, 18, 12908, 537, 12, 2867, 12, 16683, 3631, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 3639, 284, 354, 92, 18, 12908, 537, 12, 2867, 12, 16683, 3631, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 3639, 1018, 30915, 273, 1758, 12, 3030, 77, 1769, 203, 203, 3639, 7738, 39, 4962, 14667, 273, 12619, 31, 203, 3639, 7738, 3477, 7201, 14667, 273, 6604, 31, 203, 3639, 7738, 30915, 14667, 273, 6604, 31, 203, 2 ]
./full_match/43114/0x1db69e08e497639177C11e79d146f24C60FbDe60/sources/https_/github.com/traderjoe-xyz/joe-core/blob/main/contracts/traderjoe/JoeRouter02.sol
**** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityAVAXSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountAVAXMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountAVAX) { (, amountAVAX) = removeLiquidity( token, WAVAX, liquidity, amountTokenMin, amountAVAXMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20Joe(token).balanceOf(address(this))); IWAVAX(WAVAX).withdraw(amountAVAX); TransferHelper.safeTransferAVAX(to, amountAVAX); }
4,643,704
[ 1, 22122, 8961, 53, 3060, 4107, 261, 13261, 310, 14036, 17, 265, 17, 13866, 2430, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 48, 18988, 24237, 5856, 2501, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 4501, 372, 24237, 16, 203, 3639, 2254, 5034, 3844, 1345, 2930, 16, 203, 3639, 2254, 5034, 3844, 5856, 2501, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 14096, 203, 565, 262, 1071, 5024, 3849, 3387, 12, 22097, 1369, 13, 1135, 261, 11890, 5034, 3844, 5856, 2501, 13, 288, 203, 3639, 261, 16, 3844, 5856, 2501, 13, 273, 1206, 48, 18988, 24237, 12, 203, 5411, 1147, 16, 203, 5411, 678, 5856, 2501, 16, 203, 5411, 4501, 372, 24237, 16, 203, 5411, 3844, 1345, 2930, 16, 203, 5411, 3844, 5856, 2501, 2930, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 14096, 203, 3639, 11272, 203, 3639, 12279, 2276, 18, 4626, 5912, 12, 2316, 16, 358, 16, 467, 654, 39, 3462, 46, 15548, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 3639, 467, 59, 5856, 2501, 12, 59, 5856, 2501, 2934, 1918, 9446, 12, 8949, 5856, 2501, 1769, 203, 3639, 12279, 2276, 18, 4626, 5912, 5856, 2501, 12, 869, 16, 3844, 5856, 2501, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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 constant 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 constant returns (uint256); function transferFrom(address from, address to, uint256 value)public returns (bool); function approve(address spender, uint256 value)public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title 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) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @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 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 allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause()public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /** * @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)) 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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value)public returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value)public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender)public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title FFC Token * @dev FFC is PausableToken */ contract FFCToken is StandardToken, Pausable { string public constant name = "FFC"; string public constant symbol = "FFC"; uint256 public constant decimals = 18; // lock struct LockToken{ uint256 amount; uint32 time; } struct LockTokenSet{ LockToken[] lockList; } mapping ( address => LockTokenSet ) addressTimeLock; mapping ( address => bool ) lockAdminList; event TransferWithLockEvt(address indexed from, address indexed to, uint256 value,uint256 lockValue,uint32 lockTime ); /** * @dev Creates a new MPKToken instance */ constructor() public { totalSupply = 10 * (10 ** 8) * (10 ** 18); balances[0xC0FF6587381Ed1690baC9954f9Ace2768738BaDa] = totalSupply; } function transfer(address _to, uint256 _value)public whenNotPaused returns (bool) { assert ( balances[msg.sender].sub( getLockAmount( msg.sender ) ) >= _value ); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value)public whenNotPaused returns (bool) { assert ( balances[_from].sub( getLockAmount( msg.sender ) ) >= _value ); return super.transferFrom(_from, _to, _value); } function getLockAmount( address myaddress ) public view returns ( uint256 lockSum ) { uint256 lockAmount = 0; for( uint32 i = 0; i < addressTimeLock[myaddress].lockList.length; i ++ ){ if( addressTimeLock[myaddress].lockList[i].time > now ){ lockAmount += addressTimeLock[myaddress].lockList[i].amount; } } return lockAmount; } function getLockListLen( address myaddress ) public view returns ( uint256 lockAmount ){ return addressTimeLock[myaddress].lockList.length; } function getLockByIdx( address myaddress,uint32 idx ) public view returns ( uint256 lockAmount, uint32 lockTime ){ if( idx >= addressTimeLock[myaddress].lockList.length ){ return (0,0); } lockAmount = addressTimeLock[myaddress].lockList[idx].amount; lockTime = addressTimeLock[myaddress].lockList[idx].time; return ( lockAmount,lockTime ); } function transferWithLock( address _to, uint256 _value,uint256 _lockValue,uint32 _lockTime )public whenNotPaused { if( lockAdminList[msg.sender] != true ){ return; } assert( _lockTime > now ); assert( _lockValue > 0 && _lockValue <= _value ); transfer( _to, _value ); bool needNewLock = true; for( uint32 i = 0 ; i< addressTimeLock[_to].lockList.length; i ++ ){ if( addressTimeLock[_to].lockList[i].time < now ){ addressTimeLock[_to].lockList[i].time = _lockTime; addressTimeLock[_to].lockList[i].amount = _lockValue; emit TransferWithLockEvt( msg.sender,_to,_value,_lockValue,_lockTime ); needNewLock = false; break; } } if( needNewLock == true ){ // add a lock addressTimeLock[_to].lockList.length ++ ; addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].time = _lockTime; addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].amount = _lockValue; emit TransferWithLockEvt( msg.sender,_to,_value,_lockValue,_lockTime); } } function setLockAdmin(address _to,bool canUse)public onlyOwner{ lockAdminList[_to] = canUse; } function canUseLock() public view returns (bool){ return lockAdminList[msg.sender]; } }
* @dev Creates a new MPKToken instance/
constructor() public { totalSupply = 10 * (10 ** 8) * (10 ** 18); balances[0xC0FF6587381Ed1690baC9954f9Ace2768738BaDa] = totalSupply; }
10,478,417
[ 1, 2729, 279, 394, 490, 8784, 1345, 791, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 1435, 1071, 288, 203, 565, 2078, 3088, 1283, 273, 1728, 380, 261, 2163, 2826, 1725, 13, 380, 261, 2163, 2826, 6549, 1769, 203, 565, 324, 26488, 63, 20, 14626, 20, 2246, 26, 8204, 27, 7414, 21, 2671, 2313, 9349, 12124, 39, 2733, 6564, 74, 29, 37, 311, 5324, 9470, 27, 7414, 38, 69, 40, 69, 65, 273, 2078, 3088, 1283, 31, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.6; // modules import "@erc725/smart-contracts/contracts/utils/OwnableUnset.sol"; import "@erc725/smart-contracts/contracts/ERC725Y.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; // interfaces import "./ILSP6KeyManager.sol"; // libraries import "./LSP6Utils.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "../Utils/ERC165CheckerCustom.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; // constants import {_INTERFACEID_ERC1271, _ERC1271_MAGICVALUE, _ERC1271_FAILVALUE} from "../LSP0ERC725Account/LSP0Constants.sol"; import "./LSP6Constants.sol"; /** * @dev revert when address `from` does not have any permissions set * on the account linked to this Key Manager * @param from the address that does not have permissions */ error NoPermissionsSet(address from); /** * @dev address `from` is not authorised to `permission` * @param permission permission required * @param from address not-authorised */ error NotAuthorised(address from, string permission); /** * @dev address `from` is not authorised to interact with `disallowedAddress` via account * @param from address making the request * @param disallowedAddress address that `from` is not authorised to call */ error NotAllowedAddress(address from, address disallowedAddress); /** * @dev address `from` is not authorised to run `disallowedFunction` via account * @param from address making the request * @param disallowedFunction bytes4 function selector that `from` is not authorised to run */ error NotAllowedFunction(address from, bytes4 disallowedFunction); /** * @dev address `from` is not authorised to set the key `disallowedKey` on the account * @param from address making the request * @param disallowedKey a bytes32 key that `from` is not authorised to set on the ERC725Y storage */ error NotAllowedERC725YKey(address from, bytes32 disallowedKey); /** * @title Core implementation of a contract acting as a controller of an ERC725 Account, using permissions stored in the ERC725Y storage * @author Fabian Vogelsteller, Jean Cavallera * @dev all the permissions can be set on the ERC725 Account using `setData(...)` with the keys constants below */ abstract contract LSP6KeyManagerCore is ILSP6KeyManager, ERC165 { using LSP2Utils for ERC725Y; using LSP6Utils for *; using Address for address; using ECDSA for bytes32; using ERC165CheckerCustom for address; address public override account; mapping(address => mapping(uint256 => uint256)) internal _nonceStore; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == _INTERFACEID_LSP6 || interfaceId == _INTERFACEID_ERC1271 || super.supportsInterface(interfaceId); } /** * @inheritdoc ILSP6KeyManager */ function getNonce(address _from, uint256 _channel) public view override returns (uint256) { uint128 nonceId = uint128(_nonceStore[_from][_channel]); return (uint256(_channel) << 128) | nonceId; } /** * @inheritdoc IERC1271 */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view override returns (bytes4 magicValue) { address recoveredAddress = ECDSA.recover(_hash, _signature); return ( ERC725Y(account) .getPermissionsFor(recoveredAddress) .includesPermissions(_PERMISSION_SIGN) ? _ERC1271_MAGICVALUE : _ERC1271_FAILVALUE ); } /** * @inheritdoc ILSP6KeyManager */ function execute(bytes calldata _data) external payable override returns (bytes memory) { _verifyPermissions(msg.sender, _data); // solhint-disable avoid-low-level-calls (bool success, bytes memory result_) = address(account).call{ value: msg.value, gas: gasleft() }(_data); if (!success) { // solhint-disable reason-string if (result_.length < 68) revert(); // solhint-disable no-inline-assembly assembly { result_ := add(result_, 0x04) } revert(abi.decode(result_, (string))); } emit Executed(msg.value, _data); return result_.length > 0 ? abi.decode(result_, (bytes)) : result_; } /** * @inheritdoc ILSP6KeyManager */ function executeRelayCall( address _signedFor, uint256 _nonce, bytes calldata _data, bytes memory _signature ) external payable override returns (bytes memory) { require( _signedFor == address(this), "executeRelayCall: Message not signed for this keyManager" ); bytes memory blob = abi.encodePacked( address(this), // needs to be signed for this keyManager _nonce, _data ); address signer = keccak256(blob).toEthSignedMessageHash().recover( _signature ); require( _isValidNonce(signer, _nonce), "executeRelayCall: Invalid nonce" ); // increase nonce after successful verification _nonceStore[signer][_nonce >> 128]++; _verifyPermissions(signer, _data); // solhint-disable avoid-low-level-calls (bool success, bytes memory result_) = address(account).call{ value: 0, gas: gasleft() }(_data); if (!success) { // solhint-disable reason-string if (result_.length < 68) revert(); // solhint-disable no-inline-assembly assembly { result_ := add(result_, 0x04) } revert(abi.decode(result_, (string))); } emit Executed(msg.value, _data); return result_.length > 0 ? abi.decode(result_, (bytes)) : result_; } /** * @notice verify the nonce `_idx` for `_from` (obtained via `getNonce(...)`) * @dev "idx" is a 256bits (unsigned) integer, where: * - the 128 leftmost bits = channelId * and - the 128 rightmost bits = nonce within the channel * @param _from caller address * @param _idx (channel id + nonce within the channel) */ function _isValidNonce(address _from, uint256 _idx) internal view returns (bool) { // idx % (1 << 128) = nonce // (idx >> 128) = channel // equivalent to: return (nonce == _nonceStore[_from][channel] return (_idx % (1 << 128)) == (_nonceStore[_from][_idx >> 128]); } /** * @dev verify the permissions of the _from address that want to interact with the `account` * @param _from the address making the request * @param _data the payload that will be run on `account` */ function _verifyPermissions(address _from, bytes calldata _data) internal view { bytes4 erc725Function = bytes4(_data[:4]); // get the permissions of the caller bytes32 permissions = ERC725Y(account).getPermissionsFor(_from); // skip permissions check if caller has all permissions (except SIGN as not required) if (permissions.includesPermissions(_ALL_EXECUTION_PERMISSIONS)) { _validateERC725Selector(erc725Function); return; } if (permissions == bytes32(0)) revert NoPermissionsSet(_from); if (erc725Function == setDataMultipleSelector) { _verifyCanSetData(_from, permissions, _data); } else if (erc725Function == IERC725X.execute.selector) { _verifyCanExecute(_from, permissions, _data); address to = address(bytes20(_data[48:68])); _verifyAllowedAddress(_from, to); if (to.code.length > 0) { _verifyAllowedStandard(_from, to); if (_data.length >= 168) { // extract bytes4 function selector from payload passed to ERC725X.execute(...) _verifyAllowedFunction(_from, bytes4(_data[164:168])); } } } else if (erc725Function == OwnableUnset.transferOwnership.selector) { if (!permissions.includesPermissions(_PERMISSION_CHANGEOWNER)) revert NotAuthorised(_from, "TRANSFEROWNERSHIP"); } else { revert("_verifyPermissions: unknown ERC725 selector"); } } /** * @dev verify if `_from` has the required permissions to set some keys * on the linked ERC725Account * @param _from the address who want to set the keys * @param _data the ABI encoded payload `account.setData(keys, values)` * containing a list of keys-value pairs */ function _verifyCanSetData( address _from, bytes32 _permissions, bytes calldata _data ) internal view { (bytes32[] memory inputKeys, bytes[] memory inputValues) = abi.decode( _data[4:], (bytes32[], bytes[]) ); bool isSettingERC725YKeys = false; // loop through the keys we are trying to set for (uint256 ii = 0; ii < inputKeys.length; ii++) { bytes32 key = inputKeys[ii]; // prettier-ignore // if the key is a permission key if (bytes8(key) == _SET_PERMISSIONS_PREFIX) { _verifyCanSetPermissions(key, _from, _permissions); // "nullify permission keys, // so that they do not get check against allowed ERC725Y keys inputKeys[ii] = bytes32(0); } else if (key == _LSP6_ADDRESS_PERMISSIONS_ARRAY_KEY) { uint256 arrayLength = uint256(bytes32(ERC725Y(account).getData(key))); uint256 newLength = uint256(bytes32(inputValues[ii])); if (newLength > arrayLength) { if (!_permissions.includesPermissions(_PERMISSION_ADDPERMISSIONS)) revert NotAuthorised(_from, "ADDPERMISSIONS"); } else { if (!_permissions.includesPermissions(_PERMISSION_CHANGEPERMISSIONS)) revert NotAuthorised(_from, "CHANGEPERMISSIONS"); } } else if (bytes16(key) == _LSP6_ADDRESS_PERMISSIONS_ARRAY_KEY_PREFIX) { if (!_permissions.includesPermissions(_PERMISSION_CHANGEPERMISSIONS)) revert NotAuthorised(_from, "CHANGEPERMISSIONS"); // if the key is any other bytes32 key } else { isSettingERC725YKeys = true; } } if (isSettingERC725YKeys) { if (!_permissions.includesPermissions(_PERMISSION_SETDATA)) revert NotAuthorised(_from, "SETDATA"); _verifyAllowedERC725YKeys(_from, inputKeys); } } function _verifyCanSetPermissions( bytes32 _key, address _from, bytes32 _callerPermissions ) internal view { // prettier-ignore // check if some permissions are already stored under this key if (bytes32(ERC725Y(account).getData(_key)) == bytes32(0)) { // if nothing is stored under this key, // we are trying to ADD permissions for a NEW address if (!_callerPermissions.includesPermissions(_PERMISSION_ADDPERMISSIONS)) revert NotAuthorised(_from, "ADDPERMISSIONS"); } else { // if there are already a value stored under this key, // we are trying to CHANGE the permissions of an address // (that has already some EXISTING permissions set) if (!_callerPermissions.includesPermissions(_PERMISSION_CHANGEPERMISSIONS)) revert NotAuthorised(_from, "CHANGEPERMISSIONS"); } } function _verifyAllowedERC725YKeys( address _from, bytes32[] memory _inputKeys ) internal view { bytes memory allowedERC725YKeysEncoded = ERC725Y(account).getData( LSP2Utils.generateBytes20MappingWithGroupingKey( _LSP6_ADDRESS_ALLOWEDERC725YKEYS_MAP_KEY_PREFIX, bytes20(_from) ) ); // whitelist any ERC725Y key if nothing in the list if (allowedERC725YKeysEncoded.length == 0) return; bytes32[] memory allowedERC725YKeys = abi.decode( allowedERC725YKeysEncoded, (bytes32[]) ); bytes memory allowedKeySlice; bytes memory inputKeySlice; uint256 sliceLength; bool isAllowedKey; // save the not allowed key for cusom revert error bytes32 notAllowedKey; // loop through each allowed ERC725Y key retrieved from storage for (uint256 ii = 0; ii < allowedERC725YKeys.length; ii++) { // save the length of the slice // so to know which part to compare for each key we are trying to set (allowedKeySlice, sliceLength) = _extractKeySlice( allowedERC725YKeys[ii] ); // loop through each keys given as input for (uint256 jj = 0; jj < _inputKeys.length; jj++) { // skip permissions keys that have been "nulled" previously if (_inputKeys[jj] == bytes32(0)) continue; // extract the slice to compare with the allowed key inputKeySlice = BytesLib.slice( bytes.concat(_inputKeys[jj]), 0, sliceLength ); isAllowedKey = keccak256(allowedKeySlice) == keccak256(inputKeySlice); // if the keys match, the key is allowed so stop iteration if (isAllowedKey) break; // if the keys do not match, save this key as a not allowed key notAllowedKey = _inputKeys[jj]; } // if after checking all the keys given as input we did not find any not allowed key // stop checking the other allowed ERC725Y keys if (isAllowedKey == true) break; } // we always revert with the last not-allowed key that we found in the keys given as inputs if (isAllowedKey == false) revert NotAllowedERC725YKey(_from, notAllowedKey); } /** * @dev verify if `_from` has the required permissions to make an external call * via the linked ERC725Account * @param _from the address who want to run the execute function on the ERC725Account * @param _data the ABI encoded payload `account.execute(...)` */ function _verifyCanExecute( address _from, bytes32 _permissions, bytes calldata _data ) internal pure { uint256 operationType = uint256(bytes32(_data[4:36])); uint256 value = uint256(bytes32(_data[68:100])); // TODO: to be removed, as delegatecall should be allowed in the future require( operationType != 4, "_verifyCanExecute: operation 4 `DELEGATECALL` not supported" ); ( bytes32 permissionRequired, string memory operationName ) = _extractPermissionFromOperation(operationType); if (!_permissions.includesPermissions(permissionRequired)) revert NotAuthorised(_from, operationName); if ( (value > 0) && !_permissions.includesPermissions(_PERMISSION_TRANSFERVALUE) ) { revert NotAuthorised(_from, "TRANSFERVALUE"); } } /** * @dev verify if `_from` is authorised to interact with address `_to` via the linked ERC725Account * @param _from the caller address * @param _to the address to interact with */ function _verifyAllowedAddress(address _from, address _to) internal view { bytes memory allowedAddresses = ERC725Y(account).getAllowedAddressesFor( _from ); // whitelist any address if nothing in the list if (allowedAddresses.length == 0) return; address[] memory allowedAddressesList = abi.decode( allowedAddresses, (address[]) ); for (uint256 ii = 0; ii < allowedAddressesList.length; ii++) { if (_to == allowedAddressesList[ii]) return; } revert NotAllowedAddress(_from, _to); } /** * @dev if `_from` is restricted to interact with contracts that implement a specific interface, * verify that `_to` implements one of these interface. * @param _from the caller address * @param _to the address of the contract to interact with */ function _verifyAllowedStandard(address _from, address _to) internal view { bytes memory allowedStandards = ERC725Y(account).getData( LSP2Utils.generateBytes20MappingWithGroupingKey( _LSP6_ADDRESS_ALLOWEDSTANDARDS_MAP_KEY_PREFIX, bytes20(_from) ) ); // whitelist any standard interface (ERC165) if nothing in the list if (allowedStandards.length == 0) return; bytes4[] memory allowedStandardsList = abi.decode( allowedStandards, (bytes4[]) ); for (uint256 ii = 0; ii < allowedStandardsList.length; ii++) { if (_to.supportsERC165Interface(allowedStandardsList[ii])) return; } revert("Not Allowed Standards"); } /** * @dev verify if `_from` is authorised to use the linked ERC725Account * to run a specific function `_functionSelector` at a target contract * @param _from the caller address * @param _functionSelector the bytes4 function selector of the function to run * at the target contract */ function _verifyAllowedFunction(address _from, bytes4 _functionSelector) internal view { bytes memory allowedFunctions = ERC725Y(account).getAllowedFunctionsFor( _from ); // whitelist any function if nothing in the list if (allowedFunctions.length == 0) return; bytes4[] memory allowedFunctionsList = abi.decode( allowedFunctions, (bytes4[]) ); for (uint256 ii = 0; ii < allowedFunctionsList.length; ii++) { if (_functionSelector == allowedFunctionsList[ii]) return; } revert NotAllowedFunction(_from, _functionSelector); } function _validateERC725Selector(bytes4 _selector) internal pure { // prettier-ignore require( _selector == setDataMultipleSelector || _selector == IERC725X.execute.selector || _selector == OwnableUnset.transferOwnership.selector, "_validateERC725Selector: invalid ERC725 selector" ); } function _extractKeySlice(bytes32 _key) internal pure returns (bytes memory keySlice_, uint256 sliceLength_) { // check each individual bytes of the allowed key, starting from the end (right to left) for (uint256 index = 31; index >= 0; index--) { // find where the first non-empty bytes starts (skip empty bytes 0x00) if (_key[index] != 0x00) { // stop as soon as we find a non-empty byte sliceLength_ = index + 1; keySlice_ = BytesLib.slice(bytes.concat(_key), 0, sliceLength_); break; } } } /** * @dev extract the required permission + a descriptive string, based on the `_operationType` * being run via ERC725Account.execute(...) * @param _operationType 0 = CALL, 1 = CREATE, 2 = CREATE2, etc... See ERC725X docs for more infos. * @return permissionsRequired_ (bytes32) the permission associated with the `_operationType` * @return operationName_ (string) the name of the opcode associated with `_operationType` */ function _extractPermissionFromOperation(uint256 _operationType) internal pure returns (bytes32 permissionsRequired_, string memory operationName_) { require(_operationType < 5, "LSP6KeyManager: invalid operation type"); if (_operationType == 0) return (_PERMISSION_CALL, "CALL"); if (_operationType == 1) return (_PERMISSION_DEPLOY, "CREATE"); if (_operationType == 2) return (_PERMISSION_DEPLOY, "CREATE2"); if (_operationType == 3) return (_PERMISSION_STATICCALL, "STATICCALL"); } }
* @inheritdoc IERC1271/
function isValidSignature(bytes32 _hash, bytes memory _signature) public view override returns (bytes4 magicValue) { address recoveredAddress = ECDSA.recover(_hash, _signature); return ( ERC725Y(account) .getPermissionsFor(recoveredAddress) .includesPermissions(_PERMISSION_SIGN) ? _ERC1271_MAGICVALUE : _ERC1271_FAILVALUE ); }
2,560,990
[ 1, 36, 10093, 467, 654, 39, 2138, 11212, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4908, 5374, 12, 3890, 1578, 389, 2816, 16, 1731, 3778, 389, 8195, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 3890, 24, 8146, 620, 13, 203, 565, 288, 203, 3639, 1758, 24616, 1887, 273, 7773, 19748, 18, 266, 3165, 24899, 2816, 16, 389, 8195, 1769, 203, 203, 3639, 327, 261, 203, 5411, 4232, 39, 27, 2947, 61, 12, 4631, 13, 203, 7734, 263, 588, 6521, 1290, 12, 266, 16810, 1887, 13, 203, 7734, 263, 18499, 6521, 24899, 23330, 67, 11260, 13, 203, 7734, 692, 389, 654, 39, 2138, 11212, 67, 49, 22247, 4051, 203, 7734, 294, 389, 654, 39, 2138, 11212, 67, 12319, 4051, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/53935/0x862A4819BD933D09c13094878f397e4685D9eEd4/sources/src/DepositContract.sol
@dev Allows a client to add a contract to their whitelist. @param _contractAddress The address of the contract being added.
function addContractToWhitelist(address _contractAddress) external checkClientWhitelisted(msg.sender) { require(isContract(_contractAddress), "Address cannot be EOA"); bool result = contractWhitelisted[msg.sender].add(_contractAddress); require(result, "Contract is Already whitelisted"); emit ContractWhitelisted(msg.sender, _contractAddress, block.timestamp); }
3,786,457
[ 1, 19132, 279, 1004, 358, 527, 279, 6835, 358, 3675, 10734, 18, 225, 389, 16351, 1887, 1021, 1758, 434, 326, 6835, 3832, 3096, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 8924, 774, 18927, 12, 2867, 389, 16351, 1887, 13, 203, 565, 3903, 203, 565, 866, 1227, 18927, 329, 12, 3576, 18, 15330, 13, 203, 565, 288, 203, 3639, 2583, 12, 291, 8924, 24899, 16351, 1887, 3631, 315, 1887, 2780, 506, 512, 28202, 8863, 203, 3639, 1426, 563, 273, 6835, 18927, 329, 63, 3576, 18, 15330, 8009, 1289, 24899, 16351, 1887, 1769, 203, 3639, 2583, 12, 2088, 16, 315, 8924, 353, 17009, 26944, 8863, 203, 3639, 3626, 13456, 18927, 329, 12, 3576, 18, 15330, 16, 389, 16351, 1887, 16, 1203, 18, 5508, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-12-29 */ pragma solidity >=0.6.0 <0.8.0; 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); } 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; } } 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); } } } } /** * @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"); } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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 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; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract ZeroTeamTokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _cliff; uint256 private _start; uint256 private _duration; bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public { require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration"); require(duration > 0, "TokenVesting: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time"); _beneficiary = beneficiary; _revocable = revocable; _duration = duration; _cliff = start.add(cliffDuration); _start = start; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenVesting: cannot revoke"); require(!_revoked[address(token)], "TokenVesting: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); } } function _changeBeneficiary(address _newBeneficiary) internal { _beneficiary = _newBeneficiary; } }
* @notice Transfers vested tokens to beneficiary. @param token ERC20 token which is being vested/
function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); }
70,148
[ 1, 1429, 18881, 331, 3149, 2430, 358, 27641, 74, 14463, 814, 18, 225, 1147, 4232, 39, 3462, 1147, 1492, 353, 3832, 331, 3149, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3992, 12, 45, 654, 39, 3462, 1147, 13, 1071, 288, 203, 3639, 2254, 5034, 640, 9340, 72, 273, 389, 16599, 345, 429, 6275, 12, 2316, 1769, 203, 203, 3639, 2583, 12, 318, 9340, 72, 405, 374, 16, 315, 1345, 58, 10100, 30, 1158, 2430, 854, 6541, 8863, 203, 203, 3639, 389, 9340, 72, 63, 2867, 12, 2316, 25887, 273, 389, 9340, 72, 63, 2867, 12, 2316, 13, 8009, 1289, 12, 318, 9340, 72, 1769, 203, 203, 3639, 1147, 18, 4626, 5912, 24899, 70, 4009, 74, 14463, 814, 16, 640, 9340, 72, 1769, 203, 203, 3639, 3626, 13899, 26363, 12, 2867, 12, 2316, 3631, 640, 9340, 72, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3ca1E1eFa15De2bad5032e2F173D55b5E92857ED/sources/MeroTriHopCvx.sol
Used for converting between underlying and LP
uint256 public decimalMultiplier;
15,683,689
[ 1, 6668, 364, 14540, 3086, 6808, 471, 511, 52, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 6970, 23365, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0x0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title ERC20 interface */ contract AbstractERC20 { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 value); function transfer(address _to, uint256 _value) public returns (bool _success); function allowance(address owner, address spender) public constant returns (uint256 _value); function transferFrom(address from, address to, uint256 value) public returns (bool _success); function approve(address spender, uint256 value) public returns (bool _success); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed _from, address indexed _to, uint256 _value); } contract TradCoin is Ownable, AbstractERC20 { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; //address of distributor address public distributor; // The time after which Trad tokens become transferable. // Current value is July 30, 2018 23:59:59 Eastern Time. uint256 becomesTransferable = 1533009599; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; // balances allowed to transfer during locking mapping (address => uint256) internal balancesAllowedToTransfer; //mapping to show person is investor or team/project, true=>investor, false=>team/project mapping (address => bool) public isInvestor; event DistributorTransferred(address indexed _from, address indexed _to); event Allocated(address _owner, address _investor, uint256 _tokenAmount); constructor(address _distributor) public { require (_distributor != address(0x0)); name = "TradCoin"; symbol = "TRADCoin"; decimals = 18 ; totalSupply = 300e6 * 10**18; // 300 million tokens owner = msg.sender; distributor = _distributor; balances[distributor] = totalSupply; emit Transfer(0x0, owner, totalSupply); } /// manually send tokens to investor function allocateTokensToInvestors(address _to, uint256 _value) public onlyOwner returns (bool success) { require(_to != address(0x0)); require(_value > 0); uint256 unlockValue = (_value.mul(30)).div(100); // SafeMath.sub will throw if there is not enough balance. balances[distributor] = balances[distributor].sub(_value); balances[_to] = balances[_to].add(_value); balancesAllowedToTransfer[_to] = unlockValue; isInvestor[_to] = true; emit Allocated(msg.sender, _to, _value); return true; } /// manually send tokens to investor function allocateTokensToTeamAndProjects(address _to, uint256 _value) public onlyOwner returns (bool success) { require(_to != address(0x0)); require(_value > 0); // SafeMath.sub will throw if there is not enough balance. balances[distributor] = balances[distributor].sub(_value); balances[_to] = balances[_to].add(_value); emit Allocated(msg.sender, _to, _value); return true; } /** * @dev Check balance of given account address * @param owner The address account whose balance you want to know * @return balance of the account */ function balanceOf(address owner) public view returns (uint256){ return balances[owner]; } /** * @dev transfer token for a specified address (written due to backward compatibility) * @param to address to which token is transferred * @param value amount of tokens to transfer * return bool true=> transfer is succesful */ function transfer(address to, uint256 value) public returns (bool) { require(to != address(0x0)); require(value <= balances[msg.sender]); uint256 valueAllowedToTransfer; if(isInvestor[msg.sender]){ if (now >= becomesTransferable){ valueAllowedToTransfer = balances[msg.sender]; assert(value <= valueAllowedToTransfer); }else{ valueAllowedToTransfer = balancesAllowedToTransfer[msg.sender]; assert(value <= valueAllowedToTransfer); balancesAllowedToTransfer[msg.sender] = balancesAllowedToTransfer[msg.sender].sub(value); } } balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address from which token is transferred * @param to address to which token is transferred * @param value amount of tokens to transfer * @return bool true=> transfer is succesful */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(to != address(0x0)); require(value <= balances[from]); require(value <= allowed[from][msg.sender]); uint256 valueAllowedToTransfer; if(isInvestor[from]){ if (now >= becomesTransferable){ valueAllowedToTransfer = balances[from]; assert(value <= valueAllowedToTransfer); }else{ valueAllowedToTransfer = balancesAllowedToTransfer[from]; assert(value <= valueAllowedToTransfer); balancesAllowedToTransfer[from] = balancesAllowedToTransfer[from].sub(value); } } balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } //function to check available balance to transfer tokens during locking perios for investors function availableBalanceInLockingPeriodForInvestor(address owner) public view returns(uint256){ return balancesAllowedToTransfer[owner]; } /** * @dev Approve function will delegate spender to spent tokens on msg.sender behalf * @param spender ddress which is delegated * @param value tokens amount which are delegated * @return bool true=> approve is succesful */ function approve(address spender, uint256 value) public returns (bool) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev it will check amount of token delegated to spender by owner * @param owner the address which allows someone to spend fund on his behalf * @param spender address which is delegated * @return return uint256 amount of tokens left with delegator */ function allowance(address owner, address spender) public view returns (uint256) { return allowed[owner][spender]; } /** * @dev increment the spender delegated tokens * @param spender address which is delegated * @param valueToAdd tokens amount to increment * @return bool true=> operation is succesful */ function increaseApproval(address spender, uint valueToAdd) public returns (bool) { allowed[msg.sender][spender] = allowed[msg.sender][spender].add(valueToAdd); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } /** * @dev deccrement the spender delegated tokens * @param spender address which is delegated * @param valueToSubstract tokens amount to decrement * @return bool true=> operation is succesful */ function decreaseApproval(address spender, uint valueToSubstract) public returns (bool) { uint oldValue = allowed[msg.sender][spender]; if (valueToSubstract > oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldValue.sub(valueToSubstract); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } }
manually send tokens to investor SafeMath.sub will throw if there is not enough balance.
function allocateTokensToTeamAndProjects(address _to, uint256 _value) public onlyOwner returns (bool success) { require(_to != address(0x0)); require(_value > 0); balances[distributor] = balances[distributor].sub(_value); balances[_to] = balances[_to].add(_value); emit Allocated(msg.sender, _to, _value); return true; }
279,795
[ 1, 4728, 3452, 1366, 2430, 358, 2198, 395, 280, 14060, 10477, 18, 1717, 903, 604, 309, 1915, 353, 486, 7304, 11013, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10101, 5157, 774, 8689, 1876, 15298, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1338, 5541, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 92, 20, 10019, 203, 3639, 2583, 24899, 1132, 405, 374, 1769, 203, 3639, 324, 26488, 63, 2251, 19293, 65, 273, 324, 26488, 63, 2251, 19293, 8009, 1717, 24899, 1132, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 3626, 12830, 690, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Dependency file: openzeppelin-solidity/contracts/math/SafeMath.sol // pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // Dependency file: @evolutionland/common/contracts/interfaces/ISettingsRegistry.sol // pragma solidity ^0.4.24; contract ISettingsRegistry { enum SettingsValueTypes { NONE, UINT, STRING, ADDRESS, BYTES, BOOL, INT } function uintOf(bytes32 _propertyName) public view returns (uint256); function stringOf(bytes32 _propertyName) public view returns (string); function addressOf(bytes32 _propertyName) public view returns (address); function bytesOf(bytes32 _propertyName) public view returns (bytes); function boolOf(bytes32 _propertyName) public view returns (bool); function intOf(bytes32 _propertyName) public view returns (int); function setUintProperty(bytes32 _propertyName, uint _value) public; function setStringProperty(bytes32 _propertyName, string _value) public; function setAddressProperty(bytes32 _propertyName, address _value) public; function setBytesProperty(bytes32 _propertyName, bytes _value) public; function setBoolProperty(bytes32 _propertyName, bool _value) public; function setIntProperty(bytes32 _propertyName, int _value) public; function getValueTypeOf(bytes32 _propertyName) public view returns (uint /* SettingsValueTypes */ ); event ChangeProperty(bytes32 indexed _propertyName, uint256 _type); } // Dependency file: @evolutionland/common/contracts/interfaces/IAuthority.sol // pragma solidity ^0.4.24; contract IAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } // Dependency file: @evolutionland/common/contracts/DSAuth.sol // pragma solidity ^0.4.24; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/IAuthority.sol'; contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } /** * @title DSAuth * @dev The DSAuth contract is reference implement of https://github.com/dapphub/ds-auth * But in the isAuthorized method, the src from address(this) is remove for safty concern. */ contract DSAuth is DSAuthEvents { IAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(IAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == owner) { return true; } else if (authority == IAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // Dependency file: @evolutionland/common/contracts/SettingIds.sol // pragma solidity ^0.4.24; /** Id definitions for SettingsRegistry.sol Can be used in conjunction with the settings registry to get properties */ contract SettingIds { bytes32 public constant CONTRACT_RING_ERC20_TOKEN = "CONTRACT_RING_ERC20_TOKEN"; bytes32 public constant CONTRACT_KTON_ERC20_TOKEN = "CONTRACT_KTON_ERC20_TOKEN"; bytes32 public constant CONTRACT_GOLD_ERC20_TOKEN = "CONTRACT_GOLD_ERC20_TOKEN"; bytes32 public constant CONTRACT_WOOD_ERC20_TOKEN = "CONTRACT_WOOD_ERC20_TOKEN"; bytes32 public constant CONTRACT_WATER_ERC20_TOKEN = "CONTRACT_WATER_ERC20_TOKEN"; bytes32 public constant CONTRACT_FIRE_ERC20_TOKEN = "CONTRACT_FIRE_ERC20_TOKEN"; bytes32 public constant CONTRACT_SOIL_ERC20_TOKEN = "CONTRACT_SOIL_ERC20_TOKEN"; bytes32 public constant CONTRACT_OBJECT_OWNERSHIP = "CONTRACT_OBJECT_OWNERSHIP"; bytes32 public constant CONTRACT_TOKEN_LOCATION = "CONTRACT_TOKEN_LOCATION"; bytes32 public constant CONTRACT_LAND_BASE = "CONTRACT_LAND_BASE"; bytes32 public constant CONTRACT_USER_POINTS = "CONTRACT_USER_POINTS"; bytes32 public constant CONTRACT_INTERSTELLAR_ENCODER = "CONTRACT_INTERSTELLAR_ENCODER"; bytes32 public constant CONTRACT_DIVIDENDS_POOL = "CONTRACT_DIVIDENDS_POOL"; bytes32 public constant CONTRACT_TOKEN_USE = "CONTRACT_TOKEN_USE"; bytes32 public constant CONTRACT_REVENUE_POOL = "CONTRACT_REVENUE_POOL"; bytes32 public constant CONTRACT_ERC721_BRIDGE = "CONTRACT_ERC721_BRIDGE"; bytes32 public constant CONTRACT_PET_BASE = "CONTRACT_PET_BASE"; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // this can be considered as transaction fee. // Values 0-10,000 map to 0%-100% // set ownerCut to 4% // ownerCut = 400; bytes32 public constant UINT_AUCTION_CUT = "UINT_AUCTION_CUT"; // Denominator is 10000 bytes32 public constant UINT_TOKEN_OFFER_CUT = "UINT_TOKEN_OFFER_CUT"; // Denominator is 10000 // Cut referer takes on each auction, measured in basis points (1/100 of a percent). // which cut from transaction fee. // Values 0-10,000 map to 0%-100% // set refererCut to 4% // refererCut = 400; bytes32 public constant UINT_REFERER_CUT = "UINT_REFERER_CUT"; bytes32 public constant CONTRACT_LAND_RESOURCE = "CONTRACT_LAND_RESOURCE"; } // Dependency file: contracts/interfaces/ILandBase.sol // pragma solidity ^0.4.24; contract ILandBase { /* * Event */ event ModifiedResourceRate(uint indexed tokenId, address resourceToken, uint16 newResourceRate); event HasboxSetted(uint indexed tokenId, bool hasBox); event ChangedReourceRateAttr(uint indexed tokenId, uint256 attr); event ChangedFlagMask(uint indexed tokenId, uint256 newFlagMask); event CreatedNewLand(uint indexed tokenId, int x, int y, address beneficiary, uint256 resourceRateAttr, uint256 mask); function defineResouceTokenRateAttrId(address _resourceToken, uint8 _attrId) public; function setHasBox(uint _landTokenID, bool isHasBox) public; function isReserved(uint256 _tokenId) public view returns (bool); function isSpecial(uint256 _tokenId) public view returns (bool); function isHasBox(uint256 _tokenId) public view returns (bool); function getResourceRateAttr(uint _landTokenId) public view returns (uint256); function setResourceRateAttr(uint _landTokenId, uint256 _newResourceRateAttr) public; function getResourceRate(uint _landTokenId, address _resouceToken) public view returns (uint16); function setResourceRate(uint _landTokenID, address _resourceToken, uint16 _newResouceRate) public; function getFlagMask(uint _landTokenId) public view returns (uint256); function setFlagMask(uint _landTokenId, uint256 _newFlagMask) public; function resourceToken2RateAttrId(address _resourceToken) external view returns (uint256); } // Dependency file: contracts/interfaces/IMysteriousTreasure.sol // pragma solidity ^0.4.24; contract IMysteriousTreasure { function unbox(uint256 _tokenId) public returns (uint, uint, uint, uint, uint); } // Root file: contracts/MysteriousTreasure.sol pragma solidity ^0.4.23; // import "openzeppelin-solidity/contracts/math/SafeMath.sol"; // import "@evolutionland/common/contracts/interfaces/ISettingsRegistry.sol"; // import "@evolutionland/common/contracts/DSAuth.sol"; // import "@evolutionland/common/contracts/SettingIds.sol"; // import "contracts/interfaces/ILandBase.sol"; // import "contracts/interfaces/IMysteriousTreasure.sol"; contract MysteriousTreasure is DSAuth, SettingIds, IMysteriousTreasure { using SafeMath for *; bool private singletonLock = false; ISettingsRegistry public registry; // the key of resourcePool are 0,1,2,3,4 // respectively refer to gold,wood,water,fire,soil mapping (uint256 => uint256) public resourcePool; // number of box left uint public totalBoxNotOpened; // event unbox event Unbox(uint indexed tokenId, uint goldRate, uint woodRate, uint waterRate, uint fireRate, uint soilRate); /* * Modifiers */ modifier singletonLockCall() { require(!singletonLock, "Only can call once"); _; singletonLock = true; } // this need to be created in ClockAuction cotnract constructor() public { // initializeContract } function initializeContract(ISettingsRegistry _registry, uint256[5] _resources) public singletonLockCall { owner = msg.sender; registry = _registry; totalBoxNotOpened = 176; for(uint i = 0; i < 5; i++) { _setResourcePool(i, _resources[i]); } } //TODO: consider authority again // this is invoked in auction.claimLandAsset function unbox(uint256 _tokenId) public auth returns (uint, uint, uint, uint, uint) { ILandBase landBase = ILandBase(registry.addressOf(SettingIds.CONTRACT_LAND_BASE)); if(! landBase.isHasBox(_tokenId) ) { return (0,0,0,0,0); } // after unboxing, set hasBox(tokenId) to false to restrict unboxing // set hasBox to false before unboxing operations for safety reason landBase.setHasBox(_tokenId, false); uint16[5] memory resourcesReward; (resourcesReward[0], resourcesReward[1], resourcesReward[2], resourcesReward[3], resourcesReward[4]) = _computeAndExtractRewardFromPool(); address resouceToken = registry.addressOf(SettingIds.CONTRACT_GOLD_ERC20_TOKEN); landBase.setResourceRate(_tokenId, resouceToken, landBase.getResourceRate(_tokenId, resouceToken) + resourcesReward[0]); resouceToken = registry.addressOf(SettingIds.CONTRACT_WOOD_ERC20_TOKEN); landBase.setResourceRate(_tokenId, resouceToken, landBase.getResourceRate(_tokenId, resouceToken) + resourcesReward[1]); resouceToken = registry.addressOf(SettingIds.CONTRACT_WATER_ERC20_TOKEN); landBase.setResourceRate(_tokenId, resouceToken, landBase.getResourceRate(_tokenId, resouceToken) + resourcesReward[2]); resouceToken = registry.addressOf(SettingIds.CONTRACT_FIRE_ERC20_TOKEN); landBase.setResourceRate(_tokenId, resouceToken, landBase.getResourceRate(_tokenId, resouceToken) + resourcesReward[3]); resouceToken = registry.addressOf(SettingIds.CONTRACT_SOIL_ERC20_TOKEN); landBase.setResourceRate(_tokenId, resouceToken, landBase.getResourceRate(_tokenId, resouceToken) + resourcesReward[4]); // only record increment of resources emit Unbox(_tokenId, resourcesReward[0], resourcesReward[1], resourcesReward[2], resourcesReward[3], resourcesReward[4]); return (resourcesReward[0], resourcesReward[1], resourcesReward[2], resourcesReward[3], resourcesReward[4]); } // rewards ranges from [0, 2 * average_of_resourcePool_left] // if early players get high resourceReward, then the later ones will get lower. // in other words, if early players get low resourceReward, the later ones get higher. // think about snatching wechat's virtual red envelopes in groups. function _computeAndExtractRewardFromPool() internal returns(uint16,uint16,uint16,uint16,uint16) { if ( totalBoxNotOpened == 0 ) { return (0,0,0,0,0); } uint16[5] memory resourceRewards; // from fomo3d // msg.sender is always address(auction), // so change msg.sender to tx.origin uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(tx.origin)))) / (now)).add (block.number) ))); for(uint i = 0; i < 5; i++) { if (totalBoxNotOpened > 1) { // recources in resourcePool is set by owner // nad totalBoxNotOpened is set by rules // there is no need to consider overflow // goldReward, woodReward, waterReward, fireReward, soilReward // 2 ** 16 - 1 uint doubleAverage = (2 * resourcePool[i] / totalBoxNotOpened); if (doubleAverage > 65535) { doubleAverage = 65535; } uint resourceReward = seed % doubleAverage; resourceRewards[i] = uint16(resourceReward); // update resourcePool _setResourcePool(i, resourcePool[i] - resourceRewards[i]); } if(totalBoxNotOpened == 1) { resourceRewards[i] = uint16(resourcePool[i]); _setResourcePool(i, resourcePool[i] - uint256(resourceRewards[i])); } } totalBoxNotOpened--; return (resourceRewards[0],resourceRewards[1], resourceRewards[2], resourceRewards[3], resourceRewards[4]); } function _setResourcePool(uint _keyNumber, uint _resources) internal { require(_keyNumber >= 0 && _keyNumber < 5); resourcePool[_keyNumber] = _resources; } function setResourcePool(uint _keyNumber, uint _resources) public auth { _setResourcePool(_keyNumber, _resources); } function setTotalBoxNotOpened(uint _totalBox) public auth { totalBoxNotOpened = _totalBox; } }
only record increment of resources
emit Unbox(_tokenId, resourcesReward[0], resourcesReward[1], resourcesReward[2], resourcesReward[3], resourcesReward[4]);
1,766,880
[ 1, 3700, 1409, 5504, 434, 2703, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3626, 1351, 2147, 24899, 2316, 548, 16, 2703, 17631, 1060, 63, 20, 6487, 2703, 17631, 1060, 63, 21, 6487, 2703, 17631, 1060, 63, 22, 6487, 2703, 17631, 1060, 63, 23, 6487, 2703, 17631, 1060, 63, 24, 19226, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol pragma solidity ^0.4.21; /** * @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: node_modules\openzeppelin-solidity\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.4.21; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\BasicToken.sol pragma solidity ^0.4.21; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol pragma solidity ^0.4.21; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Basic.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Receiver.sol pragma solidity ^0.4.21; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } // File: node_modules\openzeppelin-solidity\contracts\AddressUtils.sol pragma solidity ^0.4.21; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721BasicToken.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: contracts\Strings.sol pragma solidity ^0.4.23; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } } // File: contracts\DefinerBasicLoan.sol pragma solidity ^0.4.23; interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } contract DefinerBasicLoan is ERC721BasicToken, ERC721Metadata { using SafeERC20 for ERC20; using SafeMath for uint; enum States { Init, //0 WaitingForLender, //1 WaitingForBorrower, //2 WaitingForCollateral, //3 WaitingForFunds, //4 Funded, //5 Finished, //6 Closed, //7 Default, //8 Cancelled //9 } address public ownerAddress; address public borrowerAddress; address public lenderAddress; string public loanId; uint public endTime; // use to check default uint public nextPaymentDateTime; // use to check default uint public daysPerInstallment; // use to calculate next payment date uint public totalLoanTerm; // in days uint public borrowAmount; // total borrowed amount uint public collateralAmount; // total collateral amount uint public installmentAmount; // amount of each installment uint public remainingInstallment; // total installment left States public currentState = States.Init; /** * TODO: change address below to actual factory address after deployment * address constant private factoryContract = 0x... */ address internal factoryContract; // = 0x38Bddc3793DbFb3dE178E3dE74cae2E223c02B85; modifier onlyFactoryContract() { require(factoryContract == 0 || msg.sender == factoryContract, "not factory contract"); _; } modifier atState(States state) { require(state == currentState, "Invalid State"); _; } modifier onlyOwner() { require(msg.sender == ownerAddress, "Invalid Owner Address"); _; } modifier onlyLender() { require(msg.sender == lenderAddress || msg.sender == factoryContract, "Invalid Lender Address"); _; } modifier onlyBorrower() { require(msg.sender == borrowerAddress || msg.sender == factoryContract, "Invalid Borrower Address"); _; } modifier notDefault() { require(now < nextPaymentDateTime, "This Contract has not yet default"); require(now < endTime, "This Contract has not yet default"); _; } /** * ERC721 Interface */ function name() public view returns (string _name) { return "DeFiner Contract"; } function symbol() public view returns (string _symbol) { return "DFINC"; } function tokenURI(uint256) public view returns (string) { return Strings.strConcat( "https://api.definer.org/OKh4I2yYpKU8S2af/definer/api/v1.0/opensea/", loanId ); } function transferFrom(address _from, address _to, uint256 _tokenId) public { require(_from != address(0)); require(_to != address(0)); super.transferFrom(_from, _to, _tokenId); lenderAddress = tokenOwner[_tokenId]; } function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); lenderAddress = tokenOwner[_tokenId]; } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); lenderAddress = tokenOwner[_tokenId]; } /** * Borrower transfer ETH to contract */ function transferCollateral() public payable /*atState(States.WaitingForCollateral)*/; /** * Check if borrower transferred correct amount of Token */ function checkCollateral() public /*atState(States.WaitingForCollateral)*/; /** * Borrower cancel the transaction is Default */ function borrowerCancel() public /*onlyLender atState(States.WaitingForLender)*/; /** * Lender cancel the transaction is Default */ function lenderCancel() public /*onlyLender atState(States.WaitingForBorrower)*/; /** * Lender transfer ETH to contract */ function transferFunds() public payable /*atState(States.WaitingForFunds)*/; /** * Check if lender transferred correct amount of Token */ function checkFunds() public /*atState(States.WaitingForFunds)*/; /** * Borrower pay back ETH or Token */ function borrowerMakePayment() public payable /*onlyBorrower atState(States.Funded) notDefault*/; /** * Borrower gets collateral back */ function borrowerReclaimCollateral() public /*onlyBorrower atState(States.Finished)*/; /** * Lender gets collateral when contract state is Default */ function lenderReclaimCollateral() public /*onlyLender atState(States.Default)*/; /** * Borrower accept loan */ function borrowerAcceptLoan() public atState(States.WaitingForBorrower) { require(msg.sender != address(0), "Invalid address."); borrowerAddress = msg.sender; currentState = States.WaitingForCollateral; } /** * Lender accept loan */ function lenderAcceptLoan() public atState(States.WaitingForLender) { require(msg.sender != address(0), "Invalid address."); lenderAddress = msg.sender; currentState = States.WaitingForFunds; } function transferETHToBorrowerAndStartLoan() internal { borrowerAddress.transfer(borrowAmount); endTime = now.add(totalLoanTerm.mul(1 days)); nextPaymentDateTime = now.add(daysPerInstallment.mul(1 days)); currentState = States.Funded; } function transferTokenToBorrowerAndStartLoan(StandardToken token) internal { require(token.transfer(borrowerAddress, borrowAmount), "Token transfer failed"); endTime = now.add(totalLoanTerm.mul(1 days)); nextPaymentDateTime = now.add(daysPerInstallment.mul(1 days)); currentState = States.Funded; } //TODO not in use yet function checkDefault() public onlyLender atState(States.Funded) returns (bool) { if (now > endTime || now > nextPaymentDateTime) { currentState = States.Default; return true; } else { return false; } } // For testing function forceDefault() public onlyOwner { currentState = States.Default; } function getLoanDetails() public view returns (address,address,address,string,uint,uint,uint,uint,uint,uint,uint,uint,uint) { // address public ownerAddress; // address public borrowerAddress; // address public lenderAddress; // string public loanId; // uint public endTime; // use to check default // uint public nextPaymentDateTime; // use to check default // uint public daysPerInstallment; // use to calculate next payment date // uint public totalLoanTerm; // in days // uint public borrowAmount; // total borrowed amount // uint public collateralAmount; // total collateral amount // uint public installmentAmount; // amount of each installment // uint public remainingInstallment; // total installment left // States public currentState = States.Init; // // return ( // nextPaymentDateTime, // remainingInstallment, // uint(currentState), // loanId, // borrowerAddress, // lenderAddress // ); return ( ownerAddress, borrowerAddress, lenderAddress, loanId, endTime, nextPaymentDateTime, daysPerInstallment, totalLoanTerm, borrowAmount, collateralAmount, installmentAmount, remainingInstallment, uint(currentState) ); } } // File: contracts\ERC20ETHLoan.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ETH */ contract ERC20ETHLoan is DefinerBasicLoan { StandardToken token; address public collateralTokenAddress; /** * NOT IN USE * WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferCollateral() public payable { revert(); } function establishContract() public { // ERC20 as collateral uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); // Ether as Fund require(address(this).balance >= borrowAmount, "Insufficient fund amount"); // Transit to Funded state transferETHToBorrowerAndStartLoan(); } /** * NOT IN USE * WHEN FUND IS ETH, CHECK IS DONE IN transferFunds() */ function checkFunds() onlyLender atState(States.WaitingForFunds) public { return establishContract(); } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); currentState = States.WaitingForLender; } /** * Lender transfer ETH to fund this contract */ function transferFunds() public payable onlyLender atState(States.WaitingForFunds) { if (address(this).balance >= borrowAmount) { establishContract(); } } /* * Borrower pay back ETH */ function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault { require(msg.value >= installmentAmount); remainingInstallment--; lenderAddress.transfer(installmentAmount); if (remainingInstallment == 0) { currentState = States.Finished; } else { nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days)); } } /* * Borrower gets collateral token back when contract completed */ function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) { uint amount = token.balanceOf(address(this)); token.transfer(borrowerAddress, amount); currentState = States.Closed; } /* * Lender gets collateral token when contract defaulted */ function lenderReclaimCollateral() public onlyLender atState(States.Default) { uint amount = token.balanceOf(address(this)); token.transfer(lenderAddress, amount); currentState = States.Closed; } } // File: contracts\ERC20ETHLoanBorrower.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ETH */ contract ERC20ETHLoanBorrower is ERC20ETHLoan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _collateralTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_collateralTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; collateralTokenAddress = _collateralTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; token = StandardToken(_collateralTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; // initialial state for borrower initiated ERC20 flow currentState = States.WaitingForCollateral; } /** * NOT IN USE * WHEN FUND IS ETH, CHECK IS DONE IN transferFunds() */ function checkFunds() onlyLender atState(States.WaitingForFunds) public { return establishContract(); } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); currentState = States.WaitingForFunds; } /** * Lender transfer ETH to fund this contract */ function transferFunds() public payable onlyLender atState(States.WaitingForFunds) { if (address(this).balance >= borrowAmount) { establishContract(); } } /* * Borrower gets collateral token back when contract completed */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { uint amount = token.balanceOf(address(this)); token.transfer(borrowerAddress, amount); currentState = States.Cancelled; } /* * Lender gets funds token back when contract is cancelled */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { // For ETH leader, no way to cancel revert(); } } // File: contracts\ERC20ETHLoanLender.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ETH */ contract ERC20ETHLoanLender is ERC20ETHLoan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _collateralTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_collateralTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; collateralTokenAddress = _collateralTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; token = StandardToken(_collateralTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; // initialial state for borrower initiated ERC20 flow currentState = States.WaitingForFunds; } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { return establishContract(); } /** * Lender transfer ETH to fund this contract */ function transferFunds() public payable onlyLender atState(States.WaitingForFunds) { if (address(this).balance >= borrowAmount) { currentState = States.WaitingForCollateral; } } /* * Borrower gets collateral token back when contract completed */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { revert(); } /* * Lender gets funds token back when contract is cancelled */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { lenderAddress.transfer(address(this).balance); currentState = States.Cancelled; } } // File: contracts\ETHERC20Loan.sol pragma solidity ^0.4.23; /** * Collateral: ETH * Borrowed: ERC20 Token */ contract ETHERC20Loan is DefinerBasicLoan { StandardToken token; address public borrowedTokenAddress; function establishContract() public { // ERC20 as collateral uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); // Ether as Fund require(address(this).balance >= borrowAmount, "Insufficient fund amount"); // Transit to Funded state transferETHToBorrowerAndStartLoan(); } /* * Borrower pay back ERC20 Token */ function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault { require(remainingInstallment > 0, "No remaining installments"); require(installmentAmount > 0, "Installment amount must be non zero"); token.transfer(lenderAddress, installmentAmount); remainingInstallment--; if (remainingInstallment == 0) { currentState = States.Finished; } else { nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days)); } } /* * Borrower gets collateral ETH back when contract completed */ function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) { borrowerAddress.transfer(address(this).balance); currentState = States.Closed; } /* * Lender gets collateral ETH when contract defaulted */ function lenderReclaimCollateral() public onlyLender atState(States.Default) { lenderAddress.transfer(address(this).balance); currentState = States.Closed; } } // File: contracts\ETHERC20LoanBorrower.sol pragma solidity ^0.4.23; /** * Collateral: ETH * Borrowed: ERC20 Token */ contract ETHERC20LoanBorrower is ETHERC20Loan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_borrowedTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; borrowedTokenAddress = _borrowedTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; token = StandardToken(_borrowedTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; currentState = States.WaitingForCollateral; } /** * Borrower transfer ETH to contract */ function transferCollateral() public payable atState(States.WaitingForCollateral) { if (address(this).balance >= collateralAmount) { currentState = States.WaitingForFunds; } } /** * */ function checkFunds() public onlyLender atState(States.WaitingForFunds) { uint amount = token.balanceOf(address(this)); require(amount >= borrowAmount, "Insufficient borrowed amount"); transferTokenToBorrowerAndStartLoan(token); } /** * NOT IN USE * WHEN COLLATERAL IS ETH, CHECK IS DONE IN transferCollateral() */ function checkCollateral() public { revert(); } /** * NOT IN USE * WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferFunds() public payable { revert(); } /* * Borrower gets collateral ETH back when contract completed */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { borrowerAddress.transfer(address(this).balance); currentState = States.Cancelled; } /* * Borrower gets collateral ETH back when contract completed */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { revert(); } } // File: contracts\ETHERC20LoanLender.sol pragma solidity ^0.4.23; /** * Collateral: ETH * Borrowed: ERC20 Token */ contract ETHERC20LoanLender is ETHERC20Loan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_borrowedTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; borrowedTokenAddress = _borrowedTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; token = StandardToken(_borrowedTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; currentState = States.WaitingForFunds; } /** * Borrower transfer ETH to contract */ function transferCollateral() public payable atState(States.WaitingForCollateral) { require(address(this).balance >= collateralAmount, "Insufficient ETH collateral amount"); transferTokenToBorrowerAndStartLoan(token); } /** * */ function checkFunds() public onlyLender atState(States.WaitingForFunds) { uint amount = token.balanceOf(address(this)); require(amount >= borrowAmount, "Insufficient fund amount"); currentState = States.WaitingForCollateral; } /** * NOT IN USE * WHEN COLLATERAL IS ETH, CHECK IS DONE IN transferCollateral() */ function checkCollateral() public { revert(); } /** * NOT IN USE * WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferFunds() public payable { revert(); } /* * Borrower gets collateral ETH back when contract completed */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { revert(); } /* * Borrower gets collateral ETH back when contract completed */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); token.transfer(lenderAddress, amount); currentState = States.Cancelled; } } // File: contracts\ERC20ERC20Loan.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ERC20 Token */ contract ERC20ERC20Loan is DefinerBasicLoan { StandardToken collateralToken; StandardToken borrowedToken; address public collateralTokenAddress; address public borrowedTokenAddress; /* * Borrower pay back Token */ function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault { require(remainingInstallment > 0, "No remaining installments"); require(installmentAmount > 0, "Installment amount must be non zero"); borrowedToken.transfer(lenderAddress, installmentAmount); remainingInstallment--; if (remainingInstallment == 0) { currentState = States.Finished; } else { nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days)); } } /* * Borrower gets collateral token back when contract completed */ function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) { uint amount = collateralToken.balanceOf(address(this)); collateralToken.transfer(borrowerAddress, amount); currentState = States.Closed; } /* * Lender gets collateral token when contract defaulted */ function lenderReclaimCollateral() public onlyLender atState(States.Default) { uint amount = collateralToken.balanceOf(address(this)); collateralToken.transfer(lenderAddress, amount); currentState = States.Closed; } } // File: contracts\ERC20ERC20LoanBorrower.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ERC20 Token */ contract ERC20ERC20LoanBorrower is ERC20ERC20Loan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _collateralTokenAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_collateralTokenAddress != _borrowedTokenAddress); require(_collateralTokenAddress != address(0), "Invalid token address"); require(_borrowedTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; collateralTokenAddress = _collateralTokenAddress; borrowedTokenAddress = _borrowedTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; collateralToken = StandardToken(_collateralTokenAddress); borrowedToken = StandardToken(_borrowedTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; currentState = States.WaitingForCollateral; } /** * NOT IN USE * WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferCollateral() public payable { revert(); } /** * NOT IN USE * WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferFunds() public payable { revert(); } /** * */ function checkFunds() public onlyLender atState(States.WaitingForFunds) { uint amount = borrowedToken.balanceOf(address(this)); require(amount >= borrowAmount, "Insufficient borrowed amount"); transferTokenToBorrowerAndStartLoan(borrowedToken); } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = collateralToken.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient Collateral Token amount"); currentState = States.WaitingForFunds; } /* * Borrower gets collateral token back when contract cancelled */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { uint amount = collateralToken.balanceOf(address(this)); collateralToken.transfer(borrowerAddress, amount); currentState = States.Cancelled; } /* * Lender gets fund token back when contract cancelled */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { revert(); } } // File: contracts\ERC20ERC20LoanLender.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ERC20 Token */ contract ERC20ERC20LoanLender is ERC20ERC20Loan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _collateralTokenAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_collateralTokenAddress != _borrowedTokenAddress); require(_collateralTokenAddress != address(0), "Invalid token address"); require(_borrowedTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; collateralTokenAddress = _collateralTokenAddress; borrowedTokenAddress = _borrowedTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; collateralToken = StandardToken(_collateralTokenAddress); borrowedToken = StandardToken(_borrowedTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; currentState = States.WaitingForFunds; } /** * NOT IN USE * WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferCollateral() public payable { revert(); } /** * NOT IN USE * WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferFunds() public payable { revert(); } /** * */ function checkFunds() public onlyLender atState(States.WaitingForFunds) { uint amount = borrowedToken.balanceOf(address(this)); require(amount >= borrowAmount, "Insufficient fund amount"); currentState = States.WaitingForCollateral; } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = collateralToken.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient Collateral Token amount"); transferTokenToBorrowerAndStartLoan(borrowedToken); } /* * Borrower gets collateral token back when contract cancelled */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { revert(); } /* * Lender gets fund token back when contract cancelled */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { uint amount = borrowedToken.balanceOf(address(this)); borrowedToken.transfer(lenderAddress, amount); currentState = States.Cancelled; } } // File: contracts\DefinerLoanFactory.sol pragma solidity ^0.4.23; library Library { struct contractAddress { address value; bool exists; } } contract CloneFactory { event CloneCreated(address indexed target, address clone); function createClone(address target) internal returns (address result) { bytes memory clone = hex"3d602d80600a3d3981f3363d3d373d3d3d363d73bebebebebebebebebebebebebebebebebebebebe5af43d82803e903d91602b57fd5bf3"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[20 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } contract DefinerLoanFactory is CloneFactory { using Library for Library.contractAddress; address public owner = msg.sender; address public ERC20ETHLoanBorrowerMasterContractAddress; address public ERC20ETHLoanLenderMasterContractAddress; address public ETHERC20LoanBorrowerMasterContractAddress; address public ETHERC20LoanLenderMasterContractAddress; address public ERC20ERC20LoanBorrowerMasterContractAddress; address public ERC20ERC20LoanLenderMasterContractAddress; mapping(address => address[]) contractMap; mapping(string => Library.contractAddress) contractById; modifier onlyOwner() { require(msg.sender == owner, "Invalid Owner Address"); _; } constructor ( address _ERC20ETHLoanBorrowerMasterContractAddress, address _ERC20ETHLoanLenderMasterContractAddress, address _ETHERC20LoanBorrowerMasterContractAddress, address _ETHERC20LoanLenderMasterContractAddress, address _ERC20ERC20LoanBorrowerMasterContractAddress, address _ERC20ERC20LoanLenderMasterContractAddress ) public { owner = msg.sender; ERC20ETHLoanBorrowerMasterContractAddress = _ERC20ETHLoanBorrowerMasterContractAddress; ERC20ETHLoanLenderMasterContractAddress = _ERC20ETHLoanLenderMasterContractAddress; ETHERC20LoanBorrowerMasterContractAddress = _ETHERC20LoanBorrowerMasterContractAddress; ETHERC20LoanLenderMasterContractAddress = _ETHERC20LoanLenderMasterContractAddress; ERC20ERC20LoanBorrowerMasterContractAddress = _ERC20ERC20LoanBorrowerMasterContractAddress; ERC20ERC20LoanLenderMasterContractAddress = _ERC20ERC20LoanLenderMasterContractAddress; } function getUserContracts(address userAddress) public view returns (address[]) { return contractMap[userAddress]; } function getContractByLoanId(string _loanId) public view returns (address) { return contractById[_loanId].value; } function createERC20ETHLoanBorrowerClone( address _collateralTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _lenderAddress ) public payable returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ERC20ETHLoanBorrowerMasterContractAddress); ERC20ETHLoanBorrower(clone).init({ _ownerAddress : owner, _borrowerAddress : msg.sender, _lenderAddress : _lenderAddress, _collateralTokenAddress : _collateralTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createERC20ETHLoanLenderClone( address _collateralTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _borrowerAddress ) public payable returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ERC20ETHLoanLenderMasterContractAddress); ERC20ETHLoanLender(clone).init({ _ownerAddress : owner, _borrowerAddress : _borrowerAddress, _lenderAddress : msg.sender, _collateralTokenAddress : _collateralTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); if (msg.value > 0) { ERC20ETHLoanLender(clone).transferFunds.value(msg.value)(); } contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createETHERC20LoanBorrowerClone( address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _lenderAddress ) public payable returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ETHERC20LoanBorrowerMasterContractAddress); ETHERC20LoanBorrower(clone).init({ _ownerAddress : owner, _borrowerAddress : msg.sender, _lenderAddress : _lenderAddress, _borrowedTokenAddress : _borrowedTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); if (msg.value >= _collateralAmount) { ETHERC20LoanBorrower(clone).transferCollateral.value(msg.value)(); } contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createETHERC20LoanLenderClone( address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _borrowerAddress ) public payable returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ETHERC20LoanLenderMasterContractAddress); ETHERC20LoanLender(clone).init({ _ownerAddress : owner, _borrowerAddress : _borrowerAddress, _lenderAddress : msg.sender, _borrowedTokenAddress : _borrowedTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createERC20ERC20LoanBorrowerClone( address _collateralTokenAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _lenderAddress ) public returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ERC20ERC20LoanBorrowerMasterContractAddress); ERC20ERC20LoanBorrower(clone).init({ _ownerAddress : owner, _borrowerAddress : msg.sender, _lenderAddress : _lenderAddress, _collateralTokenAddress : _collateralTokenAddress, _borrowedTokenAddress : _borrowedTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createERC20ERC20LoanLenderClone( address _collateralTokenAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _borrowerAddress ) public returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ERC20ERC20LoanLenderMasterContractAddress); ERC20ERC20LoanLender(clone).init({ _ownerAddress : owner, _borrowerAddress : _borrowerAddress, _lenderAddress : msg.sender, _collateralTokenAddress : _collateralTokenAddress, _borrowedTokenAddress : _borrowedTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function changeOwner(address newOwner) public onlyOwner { owner = newOwner; } }
* Check if borrower transferred correct amount of token to this contract/
function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); currentState = States.WaitingForFunds; }
1,755,007
[ 1, 1564, 309, 29759, 264, 906, 4193, 3434, 3844, 434, 1147, 358, 333, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 866, 13535, 2045, 287, 1435, 1071, 1338, 38, 15318, 264, 622, 1119, 12, 7629, 18, 15946, 1290, 13535, 2045, 287, 13, 288, 203, 565, 2254, 3844, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 2583, 12, 8949, 1545, 4508, 2045, 287, 6275, 16, 315, 5048, 11339, 4508, 2045, 287, 3844, 8863, 203, 565, 17773, 273, 29577, 18, 15946, 1290, 42, 19156, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./interface/ISqwidMarketplace.sol"; contract SqwidGovernance { struct Transaction { address to; uint256 value; bytes data; bool executed; uint256 numConfirmations; } struct OwnersChange { address ownerChanged; bool addToList; uint256 numConfirmations; } struct MinConfirmationsChange { uint256 newValue; uint256 numConfirmations; } address[] private owners; uint256 public minConfirmationsRequired; mapping(address => uint256) public addressBalance; mapping(address => bool) public isOwner; Transaction[] public transactions; // mapping from tx index => owner => bool mapping(uint256 => mapping(address => bool)) public txApproved; OwnersChange[] public ownersChanges; // mapping from owner change index => owner => bool mapping(uint256 => mapping(address => bool)) public ownersChangeApproved; MinConfirmationsChange[] public minConfirmationsChanges; // mapping from min confirmation change index => owner => bool mapping(uint256 => mapping(address => bool)) public minConfirmationsChangeApproved; event ProposeTransaction( address owner, uint256 indexed txIndex, address ownerChanged, uint256 value, bytes data ); event ExecuteTransaction(address owner, uint256 indexed txIndex); event ProposeOwnersChange( address owner, uint256 indexed ownersChangeIndex, address ownerChanged, bool addToList ); event ExecuteOwnersChange(address owner, uint256 indexed ownersChangeIndex); event ProposeMinConfirmationsChange( address owner, uint256 indexed minConfirmationsChangeIndex, uint256 newValue ); event ExecuteMinConfirmationsChange(address owner, uint256 indexed minConfirmationsChangeIndex); modifier onlyOwner() { require(isOwner[msg.sender], "Governance: Caller is not owner"); _; } modifier txExists(uint256 _txIndex) { require(_txIndex < transactions.length, "Governance: Tx does not exist"); _; } modifier txNotExecuted(uint256 _txIndex) { require(!transactions[_txIndex].executed, "Governance: Tx already executed"); _; } modifier ownersChangeExists(uint256 _ownersChangeIndex) { require( _ownersChangeIndex < ownersChanges.length, "Governance: Owners change does not exist" ); _; } modifier minConfirmationsChangeExists(uint256 _minConfirmationsChangeIndex) { require( _minConfirmationsChangeIndex < minConfirmationsChanges.length, "Governance: Min confirmations change does not exist" ); _; } constructor(address[] memory _owners, uint256 _minConfirmationsRequired) { require(_owners.length > 0, "Governance: Owners required"); require( _minConfirmationsRequired > 0 && _minConfirmationsRequired <= _owners.length, "Governance: Invalid minimum confirmations" ); for (uint256 i; i < _owners.length; i++) { address owner = _owners[i]; require(owner != address(0), "Governance: Invalid owner"); require(!isOwner[owner], "Governance: Owner not unique"); isOwner[owner] = true; owners.push(owner); } minConfirmationsRequired = _minConfirmationsRequired; } receive() external payable {} ///////////////////////////// TX WITHOUT APPROVAL ///////////////////////////////////// ///////////////////// Any of the owners can execute them ////////////////////////////// /** * Withdraws available balance from marketplace contract. */ function transferFromMarketplace(ISqwidMarketplace _marketplace) external onlyOwner { _marketplace.withdraw(); } /** * Returns available balance to be shared among all the owners. */ function getAvailableBalance() public view returns (uint256) { uint256 availableBalance = address(this).balance; for (uint256 i; i < owners.length; i++) { availableBalance -= addressBalance[owners[i]]; } return availableBalance; } /** * Shares available balance (if any) among all the owners and increments their balances. * Withdraws balance of the caller. */ function withdraw() external onlyOwner { uint256 availableBalance = getAvailableBalance(); if (availableBalance >= owners.length) { uint256 share = availableBalance / owners.length; for (uint256 i; i < owners.length; i++) { addressBalance[owners[i]] += share; } } uint256 amount = addressBalance[msg.sender]; require(amount > 0, "Governance: No Reef to be claimed"); addressBalance[msg.sender] = 0; (bool success, ) = msg.sender.call{ value: amount }(""); require(success, "Governance: Error sending REEF"); } /** * Returns array of owners. */ function getOwners() external view returns (address[] memory) { return owners; } /** * Returns total number of transaction proposals. */ function transactionsCount() external view returns (uint256) { return transactions.length; } /** * Returns total number of owners change proposals. */ function ownersChangesCount() external view returns (uint256) { return ownersChanges.length; } /** * Returns total number of minimum confirmations change proposals. */ function minConfirmationsChangesCount() external view returns (uint256) { return minConfirmationsChanges.length; } //////////////////////// EXTERNAL TX WITH APPROVAL //////////////////////////////////// ///////////// Requires a minimum of confirmations to be executed ////////////////////// /** * Creates a proposal for an external transaction. * `_to`: address to be called * `_value`: value of Reef to be sent * `_data`: data to be sent */ function proposeTransaction( address _to, uint256 _value, bytes memory _data ) external onlyOwner { uint256 txIndex = transactions.length; transactions.push( Transaction({ to: _to, value: _value, data: _data, executed: false, numConfirmations: 0 }) ); approveTransaction(txIndex); emit ProposeTransaction(msg.sender, txIndex, _to, _value, _data); } /** * Approves a transaction. */ function approveTransaction(uint256 _txIndex) public onlyOwner txExists(_txIndex) txNotExecuted(_txIndex) { require(!txApproved[_txIndex][msg.sender], "Governance: Tx already approved"); Transaction storage transaction = transactions[_txIndex]; transaction.numConfirmations++; txApproved[_txIndex][msg.sender] = true; } /** * Executes a transaction. * It should have the minimum number of confirmations required in order to be executed. */ function executeTransaction(uint256 _txIndex) public onlyOwner txExists(_txIndex) txNotExecuted(_txIndex) { Transaction storage transaction = transactions[_txIndex]; require( transaction.numConfirmations >= minConfirmationsRequired, "Governance: Tx not approved" ); transaction.executed = true; (bool success, ) = transaction.to.call{ value: transaction.value }(transaction.data); require(success, "Governance: tx failed"); emit ExecuteTransaction(msg.sender, _txIndex); } //////////////////////// INTERNAL TX WITH APPROVAL //////////////////////////////////// ///////////// Requires a minimum of confirmations to be executed ////////////////////// /** * Creates a proposal for a change in the list of owners. * `_ownerChanged`: address of the owner to be changed * `_addToList`: true --> add new owner / false --> remove existing owner */ function proposeOwnersChange(address _ownerChanged, bool _addToList) external onlyOwner { uint256 ownersChangeIndex = ownersChanges.length; ownersChanges.push( OwnersChange({ ownerChanged: _ownerChanged, addToList: _addToList, numConfirmations: 0 }) ); approveOwnersChange(ownersChangeIndex); emit ProposeOwnersChange(msg.sender, ownersChangeIndex, _ownerChanged, _addToList); } /** * Approves a change in the owners list. */ function approveOwnersChange(uint256 _ownersChangeIndex) public onlyOwner ownersChangeExists(_ownersChangeIndex) { require( !ownersChangeApproved[_ownersChangeIndex][msg.sender], "Governance: Owners change already approved" ); OwnersChange storage ownersChange = ownersChanges[_ownersChangeIndex]; ownersChange.numConfirmations++; ownersChangeApproved[_ownersChangeIndex][msg.sender] = true; } /** * Executes a change in the owners list. * It should have the minimum number of confirmations required in order to do the change. */ function executeOwnersChange(uint256 _ownersChangeIndex) public onlyOwner ownersChangeExists(_ownersChangeIndex) { OwnersChange storage ownersChange = ownersChanges[_ownersChangeIndex]; require( ownersChange.numConfirmations >= minConfirmationsRequired, "Governance: Owners change not approved" ); if (ownersChange.addToList) { require(!isOwner[ownersChange.ownerChanged], "Governance: Owner not unique"); isOwner[ownersChange.ownerChanged] = true; owners.push(ownersChange.ownerChanged); } else { require(isOwner[ownersChange.ownerChanged], "Governance: Owner not found"); isOwner[ownersChange.ownerChanged] = false; uint256 index; for (uint256 i; i < owners.length; i++) { if (owners[i] == ownersChange.ownerChanged) { index = i; break; } } owners[index] = owners[owners.length - 1]; owners.pop(); if (minConfirmationsRequired > owners.length) { minConfirmationsRequired = owners.length; } } _resetProposals(); emit ExecuteOwnersChange(msg.sender, _ownersChangeIndex); } /** * Creates a proposal for a change in the minimum number of confirmations required to execute * transactions, changes in owners and changes in minum number of confirmations. * `_newValue`: new value for the minimum number of confirmations required */ function proposeMinConfirmationsChange(uint256 _newValue) external onlyOwner { uint256 minConfirmationsChangeIndex = minConfirmationsChanges.length; minConfirmationsChanges.push( MinConfirmationsChange({ newValue: _newValue, numConfirmations: 0 }) ); approveMinConfirmationsChange(minConfirmationsChangeIndex); emit ProposeMinConfirmationsChange(msg.sender, minConfirmationsChangeIndex, _newValue); } /** * Approves a change in the minimum number of confirmations required. */ function approveMinConfirmationsChange(uint256 _minConfirmationsChangeIndex) public onlyOwner minConfirmationsChangeExists(_minConfirmationsChangeIndex) { require( !minConfirmationsChangeApproved[_minConfirmationsChangeIndex][msg.sender], "Governance: Min confirmations change already approved" ); MinConfirmationsChange storage minConfirmationsChange = minConfirmationsChanges[ _minConfirmationsChangeIndex ]; minConfirmationsChange.numConfirmations++; minConfirmationsChangeApproved[_minConfirmationsChangeIndex][msg.sender] = true; } /** * Executes a change in the minimum number of confirmations required. * It should have the minimum number of confirmations required in order to be executed. */ function executeMinConfirmationsChange(uint256 _minConfirmationsChangeIndex) public onlyOwner minConfirmationsChangeExists(_minConfirmationsChangeIndex) { MinConfirmationsChange storage minConfirmationsChange = minConfirmationsChanges[ _minConfirmationsChangeIndex ]; require( minConfirmationsChange.numConfirmations >= minConfirmationsRequired, "Governance: Min confirmations change not approved" ); require( minConfirmationsChange.newValue > 0 && minConfirmationsChange.newValue <= owners.length, "Governance: Invalid minimum confirmations" ); minConfirmationsRequired = minConfirmationsChange.newValue; _resetProposals(); emit ExecuteMinConfirmationsChange(msg.sender, _minConfirmationsChangeIndex); } /** * Resets all proposals confirmations count after the owners list or the * minConfirmationsRequired value have been modified. * Existing approvals for those proposals are invalidated. */ function _resetProposals() private { for (uint256 i; i < transactions.length; i++) { if (!transactions[i].executed) { transactions[i].numConfirmations = 0; } } for (uint256 i; i < ownersChanges.length; i++) { ownersChanges[i].numConfirmations = 0; } for (uint256 i; i < minConfirmationsChanges.length; i++) { minConfirmationsChanges[i].numConfirmations = 0; } } }
* Executes a change in the owners list. It should have the minimum number of confirmations required in order to do the change./
function executeOwnersChange(uint256 _ownersChangeIndex) public onlyOwner ownersChangeExists(_ownersChangeIndex) { OwnersChange storage ownersChange = ownersChanges[_ownersChangeIndex]; require( ownersChange.numConfirmations >= minConfirmationsRequired, "Governance: Owners change not approved" ); if (ownersChange.addToList) { require(!isOwner[ownersChange.ownerChanged], "Governance: Owner not unique"); isOwner[ownersChange.ownerChanged] = true; owners.push(ownersChange.ownerChanged); require(isOwner[ownersChange.ownerChanged], "Governance: Owner not found"); isOwner[ownersChange.ownerChanged] = false; uint256 index; for (uint256 i; i < owners.length; i++) { if (owners[i] == ownersChange.ownerChanged) { index = i; break; } } owners[index] = owners[owners.length - 1]; owners.pop(); if (minConfirmationsRequired > owners.length) { minConfirmationsRequired = owners.length; } } _resetProposals(); emit ExecuteOwnersChange(msg.sender, _ownersChangeIndex); }
12,720,711
[ 1, 9763, 279, 2549, 316, 326, 25937, 666, 18, 2597, 1410, 1240, 326, 5224, 1300, 434, 6932, 1012, 1931, 316, 1353, 358, 741, 326, 2549, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 5460, 414, 3043, 12, 11890, 5034, 389, 995, 414, 3043, 1016, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 3639, 25937, 3043, 4002, 24899, 995, 414, 3043, 1016, 13, 203, 565, 288, 203, 3639, 14223, 9646, 3043, 2502, 25937, 3043, 273, 25937, 7173, 63, 67, 995, 414, 3043, 1016, 15533, 203, 203, 3639, 2583, 12, 203, 5411, 25937, 3043, 18, 2107, 11269, 1012, 1545, 1131, 11269, 1012, 3705, 16, 203, 5411, 315, 43, 1643, 82, 1359, 30, 14223, 9646, 2549, 486, 20412, 6, 203, 3639, 11272, 203, 203, 3639, 309, 261, 995, 414, 3043, 18, 1289, 25772, 13, 288, 203, 5411, 2583, 12, 5, 291, 5541, 63, 995, 414, 3043, 18, 8443, 5033, 6487, 315, 43, 1643, 82, 1359, 30, 16837, 486, 3089, 8863, 203, 203, 5411, 353, 5541, 63, 995, 414, 3043, 18, 8443, 5033, 65, 273, 638, 31, 203, 5411, 25937, 18, 6206, 12, 995, 414, 3043, 18, 8443, 5033, 1769, 203, 5411, 2583, 12, 291, 5541, 63, 995, 414, 3043, 18, 8443, 5033, 6487, 315, 43, 1643, 82, 1359, 30, 16837, 486, 1392, 8863, 203, 203, 5411, 353, 5541, 63, 995, 414, 3043, 18, 8443, 5033, 65, 273, 629, 31, 203, 5411, 2254, 5034, 770, 31, 203, 5411, 364, 261, 11890, 5034, 277, 31, 277, 411, 25937, 18, 2469, 31, 277, 27245, 288, 203, 7734, 309, 261, 995, 414, 63, 77, 65, 422, 25937, 3043, 18, 8443, 5033, 13, 288, 203, 10792, 770, 273, 277, 31, 203, 10792, 898, 31, 203, 7734, 289, 203, 5411, 289, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "../../deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../../deps/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../../deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "../../deps/@openzeppelin/contracts-upgradeable/cryptography/MerkleProofUpgradeable.sol"; import "../../interfaces/badger/ICumulativeMultiTokenMerkleDistributor.sol"; contract BadgerTree is Initializable, AccessControlUpgradeable, ICumulativeMultiTokenMerkleDistributor, PausableUpgradeable { using SafeMathUpgradeable for uint256; struct MerkleData { bytes32 root; bytes32 contentHash; uint256 timestamp; uint256 blockNumber; } bytes32 public constant ROOT_UPDATER_ROLE = keccak256("ROOT_UPDATER_ROLE"); bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); uint256 public currentCycle; bytes32 public merkleRoot; bytes32 public merkleContentHash; uint256 public lastPublishTimestamp; uint256 public lastPublishBlockNumber; uint256 public pendingCycle; bytes32 public pendingMerkleRoot; bytes32 public pendingMerkleContentHash; uint256 public lastProposeTimestamp; uint256 public lastProposeBlockNumber; mapping(address => mapping(address => uint256)) public claimed; mapping(address => uint256) public totalClaimed; struct ExpectedClaimable { uint256 base; uint256 rate; uint256 startTime; } struct Claim { address[] tokens; uint256[] cumulativeAmounts; address account; uint256 index; uint256 cycle; } mapping(address => ExpectedClaimable) public expectedClaimable; event ExpectedClaimableSet(address indexed token, uint256 base, uint256 rate); uint256 public constant ONE_DAY = 86400; // One day in seconds function initialize( address admin, address initialUpdater, address initialGuardian ) public initializer { __AccessControl_init(); __Pausable_init_unchained(); _setupRole(DEFAULT_ADMIN_ROLE, admin); // The admin can edit all role permissions _setupRole(ROOT_UPDATER_ROLE, initialUpdater); _setupRole(GUARDIAN_ROLE, initialGuardian); } /// ===== Modifiers ===== /// @notice Admins can approve or revoke new root updaters, guardians, or admins function _onlyAdmin() internal view { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "onlyAdmin"); } /// @notice Root updaters can update the root function _onlyRootUpdater() internal view { require(hasRole(ROOT_UPDATER_ROLE, msg.sender), "onlyRootUpdater"); } /// @notice Guardians can approve the root function _onlyGuardian() internal view { require(hasRole(GUARDIAN_ROLE, msg.sender), "onlyGuardian"); } // ===== Read Functions ===== function getCurrentMerkleData() external view returns (MerkleData memory) { return MerkleData(merkleRoot, merkleContentHash, lastPublishTimestamp, lastProposeBlockNumber); } function getPendingMerkleData() external view returns (MerkleData memory) { return MerkleData(pendingMerkleRoot, pendingMerkleContentHash, lastProposeTimestamp, lastProposeBlockNumber); } function hasPendingRoot() external view returns (bool) { return pendingCycle == currentCycle.add(1); } function getClaimedFor(address user, address[] memory tokens) external view returns (address[] memory, uint256[] memory) { uint256[] memory userClaimed = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { userClaimed[i] = claimed[user][tokens[i]]; } return (tokens, userClaimed); } function getExpectedTotalClaimable(address token) public view returns (uint256) { uint256 sinceStart = now.sub(expectedClaimable[token].startTime); uint256 rateEmissions = expectedClaimable[token].rate.mul(sinceStart).div(ONE_DAY); return expectedClaimable[token].base.add(rateEmissions); } /// @dev Convenience function for encoding claim data function encodeClaim(Claim calldata claim) external pure returns (bytes memory encoded, bytes32 hash) { encoded = abi.encodePacked(claim.index, claim.account, claim.cycle, claim.claim.tokens, claim.cumulativeAmounts); hash = keccak256(encoded); } // ===== Public Actions ===== /// @notice Claim accumulated rewards for a set of tokens at a given cycle number /// @dev The primary reason to claim partially is to not claim for tokens that are of 'dust' values, saving gas for those token transfers /// @dev Amounts are made partial as well for flexibility. Perhaps a rewards program could rewards leaving assets unclaimed. function claim( address[] calldata tokensToClaim, uint256[] calldata amountsToClaim, Claim calldata claim, bytes32[] calldata merkleProof ) external whenNotPaused { require(cycle == currentCycle, "Invalid cycle"); _verifyClaimProof(claim, merkleProof); // Claim each token for (uint256 i = 0; i < claim.tokensToClaim.length; i++) { _tryClaim(claim.tokensToClaim[i], account, amountsToClaim[i], claim.cumulativeAmounts[i]); } } // ===== Root Updater Restricted ===== /// @notice Propose a new root and content hash, which will be stored as pending until approved function proposeRoot( bytes32 root, bytes32 contentHash, uint256 cycle, uint256 blockNumber ) external whenNotPaused { _onlyRootUpdater(); require(cycle == currentCycle.add(1), "Incorrect cycle"); pendingCycle = cycle; pendingMerkleRoot = root; pendingMerkleContentHash = contentHash; pendingBlockNumber = blockNumber; lastProposeTimestamp = now; lastProposeBlockNumber = block.number; emit RootProposed(cycle, pendingMerkleRoot, pendingMerkleContentHash, now, block.number); } /// ===== Guardian Restricted ===== /// @notice Approve the current pending root and content hash function approveRoot( bytes32 root, bytes32 contentHash, uint256 cycle, uint256 blockNumber ) external { _onlyGuardian(); require(root == pendingMerkleRoot, "Incorrect root"); require(contentHash == pendingMerkleContentHash, "Incorrect content hash"); require(cycle == pendingCycle, "Incorrect cycle"); currentCycle = cycle; merkleRoot = root; merkleContentHash = contentHash; publishBlockNumber = blockNumber; lastPublishTimestamp = now; lastPublishBlockNumber = block.number; emit RootUpdated(currentCycle, root, contentHash, now, block.number); } /// @notice Pause publishing of new roots function pause() external { _onlyGuardian(); _pause(); } /// @notice Unpause publishing of new roots function unpause() external { _onlyGuardian(); _unpause(); } // ===== Admin Restricted ===== /// @notice Set the expected release rate for a given token /// @param token Asset address /// @param base Base amount of token expected to be releasable. /// @param rate Daily rate of expected emissions /// @dev When updating emission schedule, set the base to the the cumulative claimable from the previous rate, and set the new rate as indended. /// @dev The startTime will be the current time, tracking the new rate into the future. function setExpectedClaimable( address token, uint256 base, uint256 rate ) external { _onlyAdmin(); expectedClaimable[token] = ExpectedClaimable(base, rate, now); ExpectedClaimableSet(token, base, rate); } function initializeTotalClaimed(address token, uint256 claimed) { _onlyAdmin(); require(totalClaimed[token] == 0, "Already has value"); totalClaimed[token] = claimed; } // ===== Internal helper functions ===== function _verifyClaimProof( address[] calldata tokens, uint256[] calldata cumulativeAmounts, uint256 index, uint256 cycle, bytes32[] calldata merkleProof ) internal { // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, msg.sender, cycle, tokens, cumulativeAmounts)); require(MerkleProofUpgradeable.verify(merkleProof, merkleRoot, node), "Invalid proof"); } function _getClaimed(address token, address account) internal returns (uint256) { return claimed[account][token]; } function _setClaimed( address token, address account, unit256 amount ) internal { claimed[account][token] = claimed[account][token].add(amount); } function _addTotalClaimed(address token, uint256 amount) internal { totalClaimed[token] = totalClaimed[token].add(amount); } function _verifyTotalClaimed(address token) internal { require(totalClaimed[token] <= _getExpectedTotalClaimable(token)); } function _tryClaim( address token, address account, uint256 amount, uint256 maxCumulativeAmount ) internal { uint256 claimed = _getClaimed(token, account); uint256 afterClaim = _setClaimed(token, account, claimed.add(amount)); require(afterClaim <= maxCumulativeAmount, "Excessive claim"); IERC20Upgradeable(tokens[i]).safeTransfer(account, amount); _addTotalClaimed(amount); _verifyTotalClaimed(token, amount); emit Claimed(account, token, amount, cycle, now, block.number); } }
@dev Convenience function for encoding claim data
function encodeClaim(Claim calldata claim) external pure returns (bytes memory encoded, bytes32 hash) { encoded = abi.encodePacked(claim.index, claim.account, claim.cycle, claim.claim.tokens, claim.cumulativeAmounts); hash = keccak256(encoded); }
12,847,535
[ 1, 14700, 445, 364, 2688, 7516, 501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2017, 9762, 12, 9762, 745, 892, 7516, 13, 3903, 16618, 1135, 261, 3890, 3778, 3749, 16, 1731, 1578, 1651, 13, 288, 203, 3639, 3749, 273, 24126, 18, 3015, 4420, 329, 12, 14784, 18, 1615, 16, 7516, 18, 4631, 16, 7516, 18, 13946, 16, 7516, 18, 14784, 18, 7860, 16, 7516, 18, 71, 11276, 6275, 87, 1769, 203, 3639, 1651, 273, 417, 24410, 581, 5034, 12, 10787, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x0C28742A434c241A0205A87322d9F0d333663937/sources/contracts/strategies/MarginswapStrategyV1.sol
* @notice Reinvest rewards from staking contract to deposit tokens @dev Reverts if the expected amount of tokens are not returned from `stakingContract` @param amount deposit tokens to reinvest/
function _reinvest(uint amount) private { stakingContract.withdrawIncentive(address(depositToken)); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee); if (address(swapPairWAVAXMfi) != address(0)) { if (address(swapPairToken) != address(0)) { uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXMfi); depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken); } else { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXMfi); } } else if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken); } _stakeDepositTokens(depositTokenAmount); emit Reinvest(totalDeposits(), totalSupply); }
4,521,757
[ 1, 426, 5768, 395, 283, 6397, 628, 384, 6159, 6835, 358, 443, 1724, 2430, 225, 868, 31537, 309, 326, 2665, 3844, 434, 2430, 854, 486, 2106, 628, 1375, 334, 6159, 8924, 68, 225, 3844, 443, 1724, 2430, 358, 283, 5768, 395, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 266, 5768, 395, 12, 11890, 3844, 13, 3238, 288, 203, 3639, 384, 6159, 8924, 18, 1918, 9446, 382, 2998, 688, 12, 2867, 12, 323, 1724, 1345, 10019, 203, 203, 3639, 2254, 4461, 14667, 273, 3844, 18, 16411, 12, 15301, 67, 8090, 41, 67, 38, 2579, 55, 2934, 2892, 12, 38, 2579, 55, 67, 2565, 26780, 916, 1769, 203, 3639, 309, 261, 5206, 14667, 405, 374, 13, 288, 203, 5411, 389, 4626, 5912, 12, 2867, 12, 266, 2913, 1345, 3631, 4461, 3178, 16, 4461, 14667, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 3981, 14667, 273, 3844, 18, 16411, 12, 15468, 67, 8090, 41, 67, 38, 2579, 55, 2934, 2892, 12, 38, 2579, 55, 67, 2565, 26780, 916, 1769, 203, 3639, 309, 261, 3666, 14667, 405, 374, 13, 288, 203, 5411, 389, 4626, 5912, 12, 2867, 12, 266, 2913, 1345, 3631, 3410, 9334, 3981, 14667, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 283, 5768, 395, 14667, 273, 3844, 18, 16411, 12, 862, 706, 3412, 882, 67, 862, 21343, 67, 38, 2579, 55, 2934, 2892, 12, 38, 2579, 55, 67, 2565, 26780, 916, 1769, 203, 3639, 309, 261, 266, 5768, 395, 14667, 405, 374, 13, 288, 203, 5411, 389, 4626, 5912, 12, 2867, 12, 266, 2913, 1345, 3631, 1234, 18, 15330, 16, 283, 5768, 395, 14667, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 443, 1724, 1345, 6275, 273, 3844, 18, 1717, 12, 5206, 14667, 2934, 1717, 12, 3666, 14667, 2934, 1717, 12, 266, 5768, 395, 14667, 1769, 203, 3639, 309, 261, 2 ]
./full_match/1/0x5C3228E02FA41e767c7A202EEE7B56C3bAb9f932/sources/closedsea/src/OperatorFilterer.sol
@notice Optimized and flexible operator filterer to abide to OpenSea's mandatory on-chain royalty enforcement in order for new collections to receive royalties. For more information, see: See: https://github.com/ProjectOpenSea/operator-filter-registry
abstract contract OperatorFilterer { address internal constant _DEFAULT_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6; address internal constant _OPERATOR_FILTER_REGISTRY = 0x000000000000AAeB6D7670E522A718067333cd4E; pragma solidity ^0.8.4; function _registerForOperatorFiltering() internal virtual { _registerForOperatorFiltering(_DEFAULT_SUBSCRIPTION, true); } function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual { assembly { subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy)) if iszero(subscriptionOrRegistrantToCopy) { break } break } function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual { assembly { subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy)) if iszero(subscriptionOrRegistrantToCopy) { break } break } for {} iszero(subscribe) {} { function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual { assembly { subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy)) if iszero(subscriptionOrRegistrantToCopy) { break } break } }
17,138,650
[ 1, 13930, 1235, 471, 16600, 1523, 3726, 1034, 264, 358, 1223, 831, 358, 3502, 1761, 69, 1807, 11791, 603, 17, 5639, 721, 93, 15006, 12980, 475, 316, 1353, 364, 394, 6980, 358, 6798, 721, 93, 2390, 606, 18, 2457, 1898, 1779, 16, 2621, 30, 2164, 30, 2333, 2207, 6662, 18, 832, 19, 4109, 3678, 1761, 69, 19, 9497, 17, 2188, 17, 9893, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 11097, 1586, 264, 288, 203, 565, 1758, 2713, 5381, 389, 5280, 67, 8362, 11133, 273, 374, 92, 23, 952, 26, 39, 449, 37, 27, 4848, 70, 7235, 70, 37, 507, 6840, 72, 42, 9803, 7228, 2046, 23622, 74, 28, 2163, 72, 39, 73, 38, 26, 31, 203, 203, 565, 1758, 2713, 5381, 389, 26110, 67, 11126, 67, 5937, 25042, 273, 374, 92, 12648, 2787, 5284, 73, 38, 26, 40, 6669, 7301, 41, 25, 3787, 37, 27, 2643, 7677, 27, 3707, 23, 4315, 24, 41, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 445, 389, 4861, 1290, 5592, 30115, 1435, 2713, 5024, 288, 203, 3639, 389, 4861, 1290, 5592, 30115, 24899, 5280, 67, 8362, 11133, 16, 638, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 4861, 1290, 5592, 30115, 12, 2867, 4915, 1162, 20175, 970, 774, 2951, 16, 1426, 9129, 13, 203, 3639, 2713, 203, 3639, 5024, 203, 565, 288, 203, 3639, 19931, 288, 203, 203, 5411, 4915, 1162, 20175, 970, 774, 2951, 519, 699, 86, 12, 10525, 16, 699, 80, 12, 10525, 16, 4915, 1162, 20175, 970, 774, 2951, 3719, 203, 7734, 309, 353, 7124, 12, 11185, 1162, 20175, 970, 774, 2951, 13, 288, 203, 10792, 898, 203, 7734, 289, 203, 7734, 898, 203, 5411, 289, 203, 565, 445, 389, 4861, 1290, 5592, 30115, 12, 2867, 4915, 1162, 20175, 970, 774, 2951, 16, 1426, 9129, 13, 203, 3639, 2713, 203, 3639, 5024, 203, 565, 288, 203, 3639, 19931, 288, 203, 203, 5411, 4915, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts/proxy/beacon/IBeacon.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./InitializeableBeaconProxy.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeaconFactory is IBeacon, Ownable { address private _implementation; InitializeableBeaconProxy public proxyAddress; /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the * beacon. */ constructor(address payable proxyAddress_, address implementation_) { proxyAddress = InitializeableBeaconProxy(proxyAddress_); _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override returns (address) { return _implementation; } function cloneProxy(bytes memory initData) external returns (address payable proxy_) { proxy_ = payable(Clones.clone(address(proxyAddress))); InitializeableBeaconProxy(proxy_).initialize(address(this), initData); } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract" ); _implementation = newImplementation; } }
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their implementation contract, which is where they will delegate all function calls. An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon./
contract UpgradeableBeaconFactory is IBeacon, Ownable { address private _implementation; InitializeableBeaconProxy public proxyAddress; event Upgraded(address indexed implementation); pragma solidity ^0.8.0; constructor(address payable proxyAddress_, address implementation_) { proxyAddress = InitializeableBeaconProxy(proxyAddress_); _setImplementation(implementation_); } function implementation() public view virtual override returns (address) { return _implementation; } function cloneProxy(bytes memory initData) external returns (address payable proxy_) { proxy_ = payable(Clones.clone(address(proxyAddress))); InitializeableBeaconProxy(proxy_).initialize(address(this), initData); } function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract" ); _implementation = newImplementation; } }
6,367,967
[ 1, 2503, 6835, 353, 1399, 316, 20998, 598, 1245, 578, 1898, 3884, 434, 288, 1919, 16329, 3886, 97, 358, 4199, 3675, 4471, 6835, 16, 1492, 353, 1625, 2898, 903, 7152, 777, 445, 4097, 18, 1922, 3410, 353, 7752, 358, 2549, 326, 4471, 326, 29203, 3143, 358, 16, 12493, 731, 15210, 326, 13263, 716, 999, 333, 29203, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17699, 429, 1919, 16329, 1733, 353, 467, 1919, 16329, 16, 14223, 6914, 288, 203, 565, 1758, 3238, 389, 30810, 31, 203, 565, 9190, 429, 1919, 16329, 3886, 1071, 2889, 1887, 31, 203, 203, 565, 871, 1948, 19305, 12, 2867, 8808, 4471, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 3885, 12, 2867, 8843, 429, 2889, 1887, 67, 16, 1758, 4471, 67, 13, 288, 203, 3639, 2889, 1887, 273, 9190, 429, 1919, 16329, 3886, 12, 5656, 1887, 67, 1769, 203, 3639, 389, 542, 13621, 12, 30810, 67, 1769, 203, 565, 289, 203, 203, 565, 445, 4471, 1435, 1071, 1476, 5024, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 30810, 31, 203, 565, 289, 203, 203, 565, 445, 3236, 3886, 12, 3890, 3778, 1208, 751, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 2867, 8843, 429, 2889, 67, 13, 203, 565, 288, 203, 3639, 2889, 67, 273, 8843, 429, 12, 2009, 5322, 18, 14056, 12, 2867, 12, 5656, 1887, 3719, 1769, 203, 3639, 9190, 429, 1919, 16329, 3886, 12, 5656, 67, 2934, 11160, 12, 2867, 12, 2211, 3631, 1208, 751, 1769, 203, 565, 289, 203, 203, 565, 445, 8400, 774, 12, 2867, 394, 13621, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 389, 542, 13621, 12, 2704, 13621, 1769, 203, 3639, 3626, 1948, 19305, 12, 2704, 13621, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 542, 13621, 12, 2867, 394, 13621, 13, 3238, 288, 203, 3639, 2583, 12, 203, 5411, 5267, 18, 291, 8924, 2 ]
./partial_match/1/0x4c43D60E14085C4Ac30F1e6Ee826d214a743f3a3/sources/SDUMToken.sol
* @dev modified transfer function that allows to safely send tokens to exchange contract. @param to The address to transfer to. @param value The amount to be transferred./
function transfer(address to, uint256 value) public returns (bool) { if (to == _exchange) { approveAndCall(to, value, new bytes(0)); super.transfer(to, value); } return true; }
4,039,656
[ 1, 7342, 7412, 445, 716, 5360, 358, 15303, 1366, 2430, 358, 7829, 6835, 18, 225, 358, 1021, 1758, 358, 7412, 358, 18, 225, 460, 1021, 3844, 358, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 203, 3639, 309, 261, 869, 422, 389, 16641, 13, 288, 203, 5411, 6617, 537, 1876, 1477, 12, 869, 16, 460, 16, 394, 1731, 12, 20, 10019, 203, 5411, 2240, 18, 13866, 12, 869, 16, 460, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 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.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; /// @dev A library for common native order operations. library LibNativeOrder { enum OrderStatus { INVALID, FILLABLE, FILLED, CANCELLED, EXPIRED } /// @dev A standard OTC or OO limit order. struct LimitOrder { IERC20TokenV06 makerToken; IERC20TokenV06 takerToken; uint128 makerAmount; uint128 takerAmount; uint128 takerTokenFeeAmount; address maker; address taker; address sender; address feeRecipient; bytes32 pool; uint64 expiry; uint256 salt; } /// @dev An RFQ limit order. struct RfqOrder { IERC20TokenV06 makerToken; IERC20TokenV06 takerToken; uint128 makerAmount; uint128 takerAmount; address maker; address taker; address txOrigin; bytes32 pool; uint64 expiry; uint256 salt; } /// @dev Info on a limit or RFQ order. struct OrderInfo { bytes32 orderHash; OrderStatus status; uint128 takerTokenFilledAmount; } uint256 private constant UINT_128_MASK = (1 << 128) - 1; uint256 private constant UINT_64_MASK = (1 << 64) - 1; uint256 private constant ADDRESS_MASK = (1 << 160) - 1; // The type hash for limit orders, which is: // keccak256(abi.encodePacked( // "LimitOrder(", // "address makerToken,", // "address takerToken,", // "uint128 makerAmount,", // "uint128 takerAmount,", // "uint128 takerTokenFeeAmount,", // "address maker,", // "address taker,", // "address sender,", // "address feeRecipient,", // "bytes32 pool,", // "uint64 expiry,", // "uint256 salt" // ")" // )) uint256 private constant _LIMIT_ORDER_TYPEHASH = 0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49; // The type hash for RFQ orders, which is: // keccak256(abi.encodePacked( // "RfqOrder(", // "address makerToken,", // "address takerToken,", // "uint128 makerAmount,", // "uint128 takerAmount,", // "address maker,", // "address taker,", // "address txOrigin,", // "bytes32 pool,", // "uint64 expiry,", // "uint256 salt" // ")" // )) uint256 private constant _RFQ_ORDER_TYPEHASH = 0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9; /// @dev Get the struct hash of a limit order. /// @param order The limit order. /// @return structHash The struct hash of the order. function getLimitOrderStructHash(LimitOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, // order.makerToken, // order.takerToken, // order.makerAmount, // order.takerAmount, // order.takerTokenFeeAmount, // order.maker, // order.taker, // order.sender, // order.feeRecipient, // order.pool, // order.expiry, // order.salt, // )) assembly { let mem := mload(0x40) mstore(mem, _LIMIT_ORDER_TYPEHASH) // order.makerToken; mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order))) // order.takerToken; mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20)))) // order.makerAmount; mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40)))) // order.takerAmount; mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60)))) // order.takerTokenFeeAmount; mstore(add(mem, 0xA0), and(UINT_128_MASK, mload(add(order, 0x80)))) // order.maker; mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0)))) // order.taker; mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0)))) // order.sender; mstore(add(mem, 0x100), and(ADDRESS_MASK, mload(add(order, 0xE0)))) // order.feeRecipient; mstore(add(mem, 0x120), and(ADDRESS_MASK, mload(add(order, 0x100)))) // order.pool; mstore(add(mem, 0x140), mload(add(order, 0x120))) // order.expiry; mstore(add(mem, 0x160), and(UINT_64_MASK, mload(add(order, 0x140)))) // order.salt; mstore(add(mem, 0x180), mload(add(order, 0x160))) structHash := keccak256(mem, 0x1A0) } } /// @dev Get the struct hash of a RFQ order. /// @param order The RFQ order. /// @return structHash The struct hash of the order. function getRfqOrderStructHash(RfqOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, // order.makerToken, // order.takerToken, // order.makerAmount, // order.takerAmount, // order.maker, // order.taker, // order.txOrigin, // order.pool, // order.expiry, // order.salt, // )) assembly { let mem := mload(0x40) mstore(mem, _RFQ_ORDER_TYPEHASH) // order.makerToken; mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order))) // order.takerToken; mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20)))) // order.makerAmount; mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40)))) // order.takerAmount; mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60)))) // order.maker; mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80)))) // order.taker; mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0)))) // order.txOrigin; mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0)))) // order.pool; mstore(add(mem, 0x100), mload(add(order, 0xE0))) // order.expiry; mstore(add(mem, 0x120), and(UINT_64_MASK, mload(add(order, 0x100)))) // order.salt; mstore(add(mem, 0x140), mload(add(order, 0x120))) structHash := keccak256(mem, 0x160) } } }
@dev A standard OTC or OO limit order.
struct LimitOrder { IERC20TokenV06 makerToken; IERC20TokenV06 takerToken; uint128 makerAmount; uint128 takerAmount; uint128 takerTokenFeeAmount; address maker; address taker; address sender; address feeRecipient; bytes32 pool; uint64 expiry; uint256 salt; }
5,394,936
[ 1, 37, 4529, 531, 15988, 578, 531, 51, 1800, 1353, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 7214, 2448, 288, 203, 3639, 467, 654, 39, 3462, 1345, 58, 7677, 312, 6388, 1345, 31, 203, 3639, 467, 654, 39, 3462, 1345, 58, 7677, 268, 6388, 1345, 31, 203, 3639, 2254, 10392, 312, 6388, 6275, 31, 203, 3639, 2254, 10392, 268, 6388, 6275, 31, 203, 3639, 2254, 10392, 268, 6388, 1345, 14667, 6275, 31, 203, 3639, 1758, 312, 6388, 31, 203, 3639, 1758, 268, 6388, 31, 203, 3639, 1758, 5793, 31, 203, 3639, 1758, 14036, 18241, 31, 203, 3639, 1731, 1578, 2845, 31, 203, 3639, 2254, 1105, 10839, 31, 203, 3639, 2254, 5034, 4286, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xC7B23589e2518d7371385ad76A824fC845fA6e0c/sources/contracts/ERC20.sol
Add Node Owners Check if the wallet has already been added Add the wallet to the nodeWallets mapping list
function addNodeWallet(address _wallet) public onlyOwner { require(!nodeWallets[_wallet], "Error: Wallet has already been added"); nodeWallets[_wallet] = true; totalNodeWallets++; emit MintTimerStarted(); }
1,917,168
[ 1, 986, 2029, 14223, 9646, 2073, 309, 326, 9230, 711, 1818, 2118, 3096, 1436, 326, 9230, 358, 326, 756, 26558, 2413, 2874, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23063, 16936, 12, 2867, 389, 19177, 13, 1071, 1338, 5541, 225, 288, 203, 3639, 2583, 12, 5, 2159, 26558, 2413, 63, 67, 19177, 6487, 315, 668, 30, 20126, 711, 1818, 2118, 3096, 8863, 203, 203, 3639, 756, 26558, 2413, 63, 67, 19177, 65, 273, 638, 31, 203, 3639, 2078, 907, 26558, 2413, 9904, 31, 203, 3639, 3626, 490, 474, 6777, 9217, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.6.4 https://hardhat.org // File @openzeppelin/contracts/utils/math/[email protected] 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; } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/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/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] 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 contracts/TokenVesting.sol //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.9; contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address owner, address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; transferOwnership(owner); } function updateTimeline(uint256 _start, uint256 _cliff, uint256 _duration) public onlyOwner { require(_cliff <= _duration); duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[address(token)] = released[address(token)].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(revocable); require(!revoked[address(token)]); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(IERC20 token) public view returns (uint256) { return vestedAmount(token).sub(released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(IERC20 token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(released[address(token)]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } }
beneficiary of tokens after they are released
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Released(uint256 amount); event Revoked(); address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; pragma solidity 0.8.9; constructor(address owner, address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; transferOwnership(owner); } function updateTimeline(uint256 _start, uint256 _cliff, uint256 _duration) public onlyOwner { require(_cliff <= _duration); duration = _duration; cliff = _start.add(_cliff); start = _start; } function release(IERC20 token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[address(token)] = released[address(token)].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } function revoke(IERC20 token) public onlyOwner { require(revocable); require(!revoked[address(token)]); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit Revoked(); } function releasableAmount(IERC20 token) public view returns (uint256) { return vestedAmount(token).sub(released[address(token)]); } function vestedAmount(IERC20 token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(released[address(token)]); if (block.timestamp < cliff) { return 0; return totalBalance; return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } function vestedAmount(IERC20 token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(released[address(token)]); if (block.timestamp < cliff) { return 0; return totalBalance; return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } else if (block.timestamp >= start.add(duration) || revoked[address(token)]) { } else { }
11,787,426
[ 1, 70, 4009, 74, 14463, 814, 434, 2430, 1839, 2898, 854, 15976, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 58, 10100, 353, 14223, 6914, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 225, 871, 10819, 72, 12, 11890, 5034, 3844, 1769, 203, 225, 871, 14477, 14276, 5621, 203, 203, 225, 1758, 1071, 27641, 74, 14463, 814, 31, 203, 203, 225, 2254, 5034, 1071, 927, 3048, 31, 203, 225, 2254, 5034, 1071, 787, 31, 203, 225, 2254, 5034, 1071, 3734, 31, 203, 203, 225, 1426, 1071, 5588, 504, 429, 31, 203, 203, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 15976, 31, 203, 225, 2874, 261, 2867, 516, 1426, 13, 1071, 22919, 31, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 29, 31, 203, 225, 3885, 12, 2867, 3410, 16, 1758, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 1937, 16, 2254, 5034, 389, 830, 3048, 16, 2254, 5034, 389, 8760, 16, 1426, 389, 9083, 504, 429, 13, 288, 203, 565, 2583, 24899, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 830, 3048, 1648, 389, 8760, 1769, 203, 203, 565, 27641, 74, 14463, 814, 273, 389, 70, 4009, 74, 14463, 814, 31, 203, 565, 5588, 504, 429, 273, 389, 9083, 504, 429, 31, 203, 565, 3734, 273, 389, 8760, 31, 203, 565, 927, 3048, 273, 389, 1937, 18, 1289, 24899, 830, 3048, 1769, 203, 565, 787, 273, 389, 1937, 31, 203, 565, 7412, 5460, 12565, 12, 8443, 1769, 203, 225, 289, 203, 203, 2 ]
// File: contracts/interfaces/IUniswapV2Router.sol interface IUniswapV2Router { function swapExactTokensForTokens(uint amountIn,uint amountOutMin,address[] calldata path,address to,uint deadline) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function WETH() external pure returns (address); } // File: contracts/interfaces/IUniswapV2Pair.sol interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/interfaces/IWETH.sol interface IWETH { function deposit() external payable; function approve(address spender, uint amount) external; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; function allowance(address owner, address spender) external view returns(uint); function balanceOf(address owner) external view returns(uint); } // File: contracts/portfolio.sol pragma solidity ^0.7.6; contract Portfolio { //info address public owner; string public name; uint public totalAssets; mapping(uint => Asset) public assets; Config config; //states bool configured; bool rulesSet; bool started; bool running; bool rebalancing; //interfaces IUniswapV2Router iUniswapRouter; IWETH iWeth; //asset structure struct Asset { string name; string symbol; address tokenAddress; uint ratio; uint amount; } //configuration structure struct Config { uint slippage; // basis points out of 10,000 uint swapTimeLimit; // time limit until swap expires in seconds address uniswapRouterAddress; address wethAddress; } constructor(address _owner, string memory _name) public { //set main info owner = _owner; name = _name; totalAssets = 0; //set states configured = false; rulesSet = false; started= false; running = false; rebalancing = false; } modifier onlyOwner { require(msg.sender == owner, "Only owner can call this function."); _; } function addAsset(string memory _name, string memory _symbol, address _address, uint _ratio) onlyOwner public { //create Asset Asset memory asset = Asset(_name, _symbol, _address, _ratio, 0); //map asset assets[totalAssets] = asset; totalAssets++; } function changeAssetRatio(uint _assetIndex, uint _assetRatio) onlyOwner public { assets[_assetIndex].ratio = _assetRatio; } function spreadToAssets() internal { //spread contract balance to assets uint totalAmount = address(this).balance; uint currentAmount = totalAmount; //for every asset for (uint i=0; i<totalAssets; i++) { //if current amount is empty if (currentAmount == 0) { break; } //get asset and ratio Asset memory asset = assets[i]; uint assetRatio = asset.ratio; if (assetRatio == 0) { break; } //calculate amountPerAsset uint amountPerAsset = totalAmount * assetRatio / 10000; //if current amount is more than amount to asset if (amountPerAsset <= currentAmount) { //buy asset for amount buyAsset(i, amountPerAsset); //adjust current amount if (amountPerAsset == currentAmount) { currentAmount = 0; } else { currentAmount -= amountPerAsset; } } else { //buy remaining current amount and set to 0 buyAsset(i, currentAmount); currentAmount = 0; } } } function buyAsset(uint currentIndex, uint amountIn) internal { //set asset data Asset memory asset = assets[currentIndex]; address buyingAddress = asset.tokenAddress; address wethAddress = config.wethAddress; require(amountIn <= address(this).balance, "Can't send more than current balance"); if (buyingAddress == wethAddress) { //deposit to Wrapped WETH iWeth.deposit{value: amountIn}(); } else { //get swap config uint slippage = config.slippage; uint swapTimeLimit = config.swapTimeLimit; //set path address[] memory path = new address[](2); path[0] = wethAddress; path[1] = buyingAddress; //get amounts out uint[] memory amountsOut = iUniswapRouter.getAmountsOut(amountIn, path); uint tokenOutput = amountsOut[1]; //calculate slippage uint amountOutMin = tokenOutput * (10000 - slippage) / 10000; //set deadline uint deadline = block.timestamp + swapTimeLimit; //swap Eth for tokens and set return amounts uint[] memory amounts = iUniswapRouter.swapExactETHForTokens{value: amountIn}(amountOutMin, path, address(this), deadline); } //update balance updateAssetBalance(currentIndex); } function updateAssetBalance(uint currentIndex) internal { Asset memory asset = assets[currentIndex]; //set balance uint balance; //set Weth address address wethAddress = config.wethAddress; if (asset.tokenAddress == wethAddress) { //get balance balance = iWeth.balanceOf(address(this)); } else { //create pair instance IUniswapV2Pair pair = IUniswapV2Pair(asset.tokenAddress); //get balance balance = pair.balanceOf(address(this)); } //update balance assets[currentIndex].amount = balance; } function rebalance() onlyOwner public { //set rebalancing true rebalancing = true; //empty assets emptyAssets(); //spread to assets spreadToAssets(); //set rebalancing back to false rebalancing = false; } function emptyAssets() onlyOwner internal { //for every asset for (uint i=0; i<totalAssets; i++) { //get asset and ratio Asset memory asset = assets[i]; //if asset balance not empty if (asset.amount > 0) { //empty asset emptyAsset(i); } } } function emptyAsset(uint currentIndex) internal { //set asset data Asset memory asset = assets[currentIndex]; address sellingAddress = asset.tokenAddress; address wethAddress = config.wethAddress; //get swap config uint slippage = config.slippage; uint swapTimeLimit = config.swapTimeLimit; require(asset.amount > 0, "Asset is already empty"); if (sellingAddress == wethAddress) { //deposit to Wrapped WETH iWeth.withdraw(asset.amount); } else { //set path address[] memory path = new address[](2); path[0] = sellingAddress; path[1] = wethAddress; //get amounts out uint[] memory amountsOut = iUniswapRouter.getAmountsOut(asset.amount, path); uint tokenOutput = amountsOut[1]; //calculate slippage uint amountOutMin = tokenOutput * (10000 - slippage) / 10000; //set deadline uint deadline = block.timestamp + swapTimeLimit; IUniswapV2Pair pair = IUniswapV2Pair(sellingAddress); pair.approve(address(iUniswapRouter), asset.amount); //swap Eth for tokens and set return amounts iUniswapRouter.swapExactTokensForETH(asset.amount, amountOutMin, path, address(this), deadline); } //update asset balance updateAssetBalance(currentIndex); } function configure(uint _slippage, uint _swapTimeLimit, address _uniswapRouterAddress, address _wethAddress) onlyOwner public { config = Config({ slippage: _slippage, swapTimeLimit: _swapTimeLimit, uniswapRouterAddress: _uniswapRouterAddress, wethAddress:_wethAddress }); //set interface instances iUniswapRouter = IUniswapV2Router(config.uniswapRouterAddress); iWeth = IWETH(config.wethAddress); //set configured to true configured = true; } function rename(string memory newName) onlyOwner public { name = newName; } function deposit() public payable { require(configured, "Configure portfolio"); if (!rebalancing) { spreadToAssets(); } } function withdraw(uint amount) onlyOwner public { //set state rebalancing = true; emptyAssets(); //transfer to owner owner.call{value: amount}(""); spreadToAssets(); rebalancing = false; } function withdrawAll() onlyOwner public { //set state rebalancing = true; emptyAssets(); //transfer to owner owner.call{value: address(this).balance}(""); spreadToAssets(); rebalancing = false; } function getTotalAssets() public view returns (uint) { return totalAssets; } function getAssetDetails(uint i) public view returns (string memory, string memory, address, uint, uint) { return (assets[i].name, assets[i].symbol, assets[i].tokenAddress, assets[i].ratio, assets[i].amount); } receive() external payable { deposit(); } } // File: contracts/wealthWallet.sol pragma solidity ^0.7.6; contract WealthWallet { address public owner; uint public totalPortfolios; mapping(uint => Portfolio) public portfolios; bool public defaultSet; uint public defaultPortfolio; constructor(address _owner) public { owner = _owner; defaultSet = false; totalPortfolios = 0; } modifier onlyOwner { require(msg.sender == owner, "Only owner can call this function."); _; } function createPortfolio(string memory _name) onlyOwner public { Portfolio portfolio = new Portfolio(owner, _name); portfolios[totalPortfolios] = portfolio; //if there is no default portfolio if (!defaultSet) { //set default to this defaultPortfolio = totalPortfolios; defaultSet = true; } //update total portfolios totalPortfolios+=1; } function addFunds() public payable { require(defaultSet, "Create a portfolio"); fundPortfolio(defaultPortfolio); } function fundPortfolio(uint portfolioIndex) public payable { //get portfolio Portfolio portfolio = portfolios[portfolioIndex]; //fund portfolio with msg value address(portfolio).call{value: msg.value}(""); } function setDefault(uint portfolioIndex) onlyOwner public { require(portfolioIndex < totalPortfolios, "Portfolio doesn't exist"); //sets new default portfolio defaultPortfolio = portfolioIndex; } function getOwner() public view returns (address) { return owner; } function getTotalPortfolios() public view returns (uint) { return totalPortfolios; } function getPortfolio(uint portfolioIndex) public view returns (address) { return address(portfolios[portfolioIndex]); } receive() external payable { addFunds(); } } // File: contracts/wealthWalletFactory.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; contract WealthWalletFactory { mapping(address => WealthWallet) public wealthWallets; function createWealthWallet() external { require(address(wealthWallets[msg.sender]) == address(0), "Wealthwallet already exists"); //create wealth wallet WealthWallet wealthWallet = new WealthWallet(msg.sender); //map wealth wallet to sender wealthWallets[msg.sender] = wealthWallet; } function getWealthWallet() external view returns (address) { return address(wealthWallets[msg.sender]); } }
update total portfolios
totalPortfolios+=1;
2,446,640
[ 1, 2725, 2078, 1756, 9002, 7441, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 2617, 9002, 7441, 15, 33, 21, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/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: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: contracts/LilHeroes.sol //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; /** * @dev Implementation of Non-Fungible Token Standard (ERC-721) * This contract is designed to be ready-to-use and versatile. */ contract LilHeroes is ERC721URIStorage, Ownable, Pausable { // General constants enum mintTypes {PRIVATE, WHITELIST, RAFFLE, PUBLIC} uint256 public maxItems = 7777; // Maximum items in the collection uint256 public price = 0.4 ether; // Price for minting one NFT uint256 public totalSupply; // number of NFTs minted thus far address internal __walletTreasury; // Address of the treasury wallet address internal __walletSignature; // Address of the treasury wallet string internal __baseURI; // Base URI for the metadata string internal __extensionURI = ""; // Extension of the URI // Constants for the private uint256 public privateMaxMintsPerTx = 10; // Maximum number of mints per transaction uint256 public privateMaxMintsPerWallet = 50; // Maximum number of mint per wallet uint256 public privateStartTime = 1642352400; // UTC timestamp when minting is open bool public privateIsActive = false; // If the mint is active mapping(address => uint256) public privateAmountMinted; // Keep track of the amount mint during the private // Constants for the whitelist uint256 public whitelistMaxMintsPerTx = 2; // Maximum number of mints per transaction uint256 public whitelistMaxMintsPerWallet = 2; // Maximum number of mint per wallet uint256 public whitelistStartTime = 1642352400; // UTC timestamp when minting is open bool public whitelistIsActive = false; // If the mint is active mapping(address => uint256) public whitelistAmountMinted; // Keep track of the amount mint during the whitelist // Constants for the raffle uint256 public raffleMaxMintsPerTx = 2; // Maximum number of mints per transaction uint256 public raffleMaxMintsPerWallet = 2; // Maximum number of mint per wallet uint256 public raffleStartTime = 1642359600; // UTC timestamp when minting is open bool public raffleIsActive = false; // If the mint is active mapping(address => uint256) public raffleAmountMinted; // Keep track of the amount mint during the raffle // Constants for the public sale uint256 public publicMaxMintsPerTx = 2; // Maximum number of mints per transaction bool public publicIsActive = false; // If the mint is active constructor( string memory name_, string memory symbol_, address walletTreasury_, address walletSignature_, string memory baseURI_ ) ERC721(name_, symbol_) { __baseURI = baseURI_; __walletTreasury = walletTreasury_; __walletSignature = walletSignature_; } /** * Set the new mint per tx allowed * @param _type The type of of maximum tx to change * @param _newMax The new maximum per tx allowed **/ function setMaxMintsPerTx(uint256 _type, uint256 _newMax) external onlyOwner { if (_type == uint256(mintTypes.WHITELIST)) { whitelistMaxMintsPerTx = _newMax; } else if (_type == uint256(mintTypes.PRIVATE)) { privateMaxMintsPerTx = _newMax; } else if (_type == uint256(mintTypes.RAFFLE)) { raffleMaxMintsPerTx = _newMax; } else if (_type == uint256(mintTypes.PUBLIC)) { publicMaxMintsPerTx = _newMax; } } /** * Set the new mint per wallet allowed * @param _type The type of of maximum tx to change * @param _newMax The new maximum per tx allowed **/ function setMaxMintsPerWallet(uint256 _type, uint256 _newMax) external onlyOwner { if (_type == uint256(mintTypes.WHITELIST)) { whitelistMaxMintsPerWallet = _newMax; } else if (_type == uint256(mintTypes.PRIVATE)) { privateMaxMintsPerWallet = _newMax; } else if (_type == uint256(mintTypes.RAFFLE)) { raffleMaxMintsPerWallet = _newMax; } } /** * Set the new start time * @param _type The type of of maximum tx to change * @param _startTime The new start time (format: timestamp) **/ function setStartTime(uint256 _type, uint256 _startTime) external onlyOwner { if (_type == uint256(mintTypes.WHITELIST)) { whitelistStartTime = _startTime; } else if (_type == uint256(mintTypes.PRIVATE)) { privateStartTime = _startTime; } else if (_type == uint256(mintTypes.RAFFLE)) { raffleStartTime = _startTime; } } /** * Set if the mint is active * @param _type The type of of maximum tx to change * @param _isActive The new state **/ function setIsActive(uint256 _type, bool _isActive) external onlyOwner { if (_type == uint256(mintTypes.WHITELIST)) { whitelistIsActive = _isActive; } else if (_type == uint256(mintTypes.PRIVATE)) { privateIsActive = _isActive; } else if (_type == uint256(mintTypes.RAFFLE)) { raffleIsActive = _isActive; } else if (_type == uint256(mintTypes.PUBLIC)) { publicIsActive = _isActive; } } /** * Set the new price * @param _price The new price **/ function setPrice(uint256 _price) external onlyOwner { price = _price; } /** * Set the new max items * @param _max The new price **/ function setMaxItems(uint256 _max) external onlyOwner { maxItems = _max; } /** * Set the new wallet treasury * @param _wallet The eth address **/ function setWalletTreasury(address _wallet) external onlyOwner { __walletTreasury = _wallet; } /** * Set the new wallet signature * @param _wallet The eth address **/ function setWalletSignature(address _wallet) external onlyOwner { __walletSignature = _wallet; } /** * Set the new base uri for metadata * @param _newBaseURI The new base uri **/ function setBaseURI(string memory _newBaseURI) external onlyOwner { __baseURI = _newBaseURI; } /** * Set the new extension of the uri * @param _newExtensionURI The new base uri **/ function setExtensionURI(string memory _newExtensionURI) external onlyOwner { __extensionURI = _newExtensionURI; } /** * Get the base url **/ function _baseURI() internal view override returns (string memory) { return __baseURI; } /** * Get the token uri of the metadata for a specific token * @param tokenId The token id **/ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (bytes(__extensionURI).length == 0){ return super.tokenURI(tokenId); } return string(abi.encodePacked(super.tokenURI(tokenId), __extensionURI)); } /** * Mint for the private sale. We check if the wallet is authorized and how mint it has already done * @param numToMint The number of token to mint * @param signature The signature **/ function mintPrivate(uint256 numToMint, bytes memory signature) external payable { require(block.timestamp > privateStartTime, "minting not open yet"); require(privateIsActive == true, "minting not activated"); require(verify(signature, msg.sender), "wallet is not whitelisted"); require(privateAmountMinted[msg.sender] + numToMint <= privateMaxMintsPerWallet, "too many tokens allowed per wallet"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= privateMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } privateAmountMinted[msg.sender] = privateAmountMinted[msg.sender] + numToMint; totalSupply += numToMint; } /** * Mint for the whitelist. We check if the wallet is authorized and how mint it has already done * @param numToMint The number of token to mint * @param signature The signature **/ function mintWhitelist(uint256 numToMint, bytes memory signature) external payable { require(block.timestamp > whitelistStartTime, "minting not open yet"); require(whitelistIsActive == true, "minting not activated"); require(verify(signature, msg.sender), "wallet is not whitelisted"); require(whitelistAmountMinted[msg.sender] + numToMint <= whitelistMaxMintsPerWallet, "too many tokens allowed per wallet"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= whitelistMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } whitelistAmountMinted[msg.sender] = whitelistAmountMinted[msg.sender] + numToMint; totalSupply += numToMint; } /** * Mint for the raffle. We check if the wallet is authorized and how mint it has already done * @param numToMint The number of token to mint * @param signature The signature **/ function mintRaffle(uint256 numToMint, bytes memory signature) external payable { require(block.timestamp > raffleStartTime, "minting not open yet"); require(raffleIsActive == true, "minting not activated"); require(verify(signature, msg.sender), "wallet is not whitelisted"); require(raffleAmountMinted[msg.sender] + numToMint <= raffleMaxMintsPerWallet, "too many tokens allowed per wallet"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= raffleMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } raffleAmountMinted[msg.sender] = raffleAmountMinted[msg.sender] + numToMint; totalSupply += numToMint; } /** * Mint for the public. * @param numToMint The number of token to mint **/ function mintPublic(uint256 numToMint) external payable whenNotPaused { require(publicIsActive == true, "minting not activated"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= publicMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } totalSupply += numToMint; } /** * Airdrop * @param recipients The list of address to send to * @param amounts The amount to send to each of address **/ function airdrop(address[] memory recipients, uint256[] memory amounts) external onlyOwner { require(recipients.length == amounts.length, "arrays have different lengths"); for (uint256 i=0; i < recipients.length; i++){ for(uint256 j=totalSupply; j < (totalSupply + amounts[i]); j++){ _mint(recipients[i], j+1); } totalSupply += amounts[i]; } } /** * Verify if the signature is legit * @param signature The signature to verify * @param target The target address to find **/ function verify(bytes memory signature, address target) public view returns (bool) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(signature); bytes32 senderHash = keccak256(abi.encodePacked(target)); //return (owner() == address(ecrecover(senderHash, v, r, s))); return (__walletSignature == address(ecrecover(senderHash, v, r, s))); } /** * Split the signature to verify * @param signature The signature to verify **/ function splitSignature(bytes memory signature) public pure returns (uint8, bytes32, bytes32) { require(signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(signature, 32)) // second 32 bytes s := mload(add(signature, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(signature, 96))) } return (v, r, s); } /** * Burns `tokenId`. See {ERC721-_burn}. The caller must own `tokenId` or be an approved operator. * @param tokenId The ID of the token to burn */ function burn(uint256 tokenId) public virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not owner nor approved"); _burn(tokenId); } /** * Withdraw the balance from the contract */ function withdraw() external payable onlyOwner returns (bool success) { (success,) = payable(__walletTreasury).call{value: address(this).balance}(""); } }
If the mint is active
bool public raffleIsActive = false;
14,759,965
[ 1, 2047, 326, 312, 474, 353, 2695, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 767, 1403, 298, 2520, 3896, 8227, 273, 629, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./interfaces/ICollectionContractInitializer.sol"; import "./interfaces/ICollectionFactory.sol"; import "./interfaces/IGetRoyalties.sol"; import "./interfaces/IProxyCall.sol"; import "./interfaces/ITokenCreator.sol"; import "./interfaces/ITokenCreatorPaymentAddress.sol"; import "./interfaces/IGetFees.sol"; import "./libraries/AccountMigrationLibrary.sol"; import "./libraries/ProxyCall.sol"; import "./libraries/BytesLibrary.sol"; import "./interfaces/IRoyaltyInfo.sol"; /** * @title A collection of NFTs. * @notice All NFTs from this contract are minted by the same creator. * A 10% royalty to the creator is included which may be split with collaborators. */ contract CollectionContract is ICollectionContractInitializer, IGetRoyalties, IGetFees, IRoyaltyInfo, ITokenCreator, ITokenCreatorPaymentAddress, ERC721BurnableUpgradeable { using AccountMigrationLibrary for address; using AddressUpgradeable for address; using BytesLibrary for bytes; using ProxyCall for IProxyCall; uint256 private constant ROYALTY_IN_BASIS_POINTS = 1000; uint256 private constant ROYALTY_RATIO = 10; /** * @notice The baseURI to use for the tokenURI, if undefined then `ipfs://` is used. */ string private baseURI_; /** * @dev Stores hashes minted to prevent duplicates. */ mapping(string => bool) private cidToMinted; /** * @notice The factory which was used to create this collection. * @dev This is used to read common config. */ ICollectionFactory public immutable collectionFactory; /** * @notice The tokenId of the most recently created NFT. * @dev Minting starts at tokenId 1. Each mint will use this value + 1. */ uint256 public latestTokenId; /** * @notice The max tokenId which can be minted, or 0 if there's no limit. * @dev This value may be set at any time, but once set it cannot be increased. */ uint256 public maxTokenId; /** * @notice The owner/creator of this NFT collection. */ address payable public owner; /** * @dev Stores an optional alternate address to receive creator revenue and royalty payments. * The target address may be a contract which could split or escrow payments. */ mapping(uint256 => address payable) private tokenIdToCreatorPaymentAddress; /** * @dev Tracks how many tokens have been burned, used to calc the total supply efficiently. */ uint256 private burnCounter; /** * @dev Stores a CID for each NFT. */ mapping(uint256 => string) private _tokenCIDs; event BaseURIUpdated(string baseURI); event CreatorMigrated(address indexed originalAddress, address indexed newAddress); event MaxTokenIdUpdated(uint256 indexed maxTokenId); event Minted(address indexed creator, uint256 indexed tokenId, string indexed indexedTokenCID, string tokenCID); event NFTOwnerMigrated(uint256 indexed tokenId, address indexed originalAddress, address indexed newAddress); event PaymentAddressMigrated( uint256 indexed tokenId, address indexed originalAddress, address indexed newAddress, address originalPaymentAddress, address newPaymentAddress ); event SelfDestruct(address indexed owner); event TokenCreatorPaymentAddressSet( address indexed fromPaymentAddress, address indexed toPaymentAddress, uint256 indexed tokenId ); modifier onlyOwner() { require(msg.sender == owner, "CollectionContract: Caller is not owner"); _; } modifier onlyOperator() { require(collectionFactory.rolesContract().isOperator(msg.sender), "CollectionContract: Caller is not an operator"); _; } /** * @dev The constructor for a proxy can only be used to assign immutable variables. */ constructor(address _collectionFactory) { require(_collectionFactory.isContract(), "CollectionContract: collectionFactory is not a contract"); collectionFactory = ICollectionFactory(_collectionFactory); } /** * @notice Called by the factory on creation. * @dev This may only be called once. */ function initialize( address payable _creator, string memory _name, string memory _symbol ) external initializer { require(msg.sender == address(collectionFactory), "CollectionContract: Collection must be created via the factory"); __ERC721_init_unchained(_name, _symbol); owner = _creator; } /** * @notice Allows the owner to mint an NFT defined by its metadata path. */ function mint(string memory tokenCID) public returns (uint256 tokenId) { tokenId = _mint(tokenCID); } /** * @notice Allows the owner to mint and sets approval for all for the provided operator. * @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval * transaction before starting an auction. */ function mintAndApprove(string memory tokenCID, address operator) public returns (uint256 tokenId) { tokenId = _mint(tokenCID); setApprovalForAll(operator, true); } /** * @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address. */ function mintWithCreatorPaymentAddress(string memory tokenCID, address payable tokenCreatorPaymentAddress) public returns (uint256 tokenId) { require(tokenCreatorPaymentAddress != address(0), "CollectionContract: tokenCreatorPaymentAddress is required"); tokenId = mint(tokenCID); _setTokenCreatorPaymentAddress(tokenId, tokenCreatorPaymentAddress); } /** * @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address. * Also sets approval for all for the provided operator. * @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval * transaction before starting an auction. */ function mintWithCreatorPaymentAddressAndApprove( string memory tokenCID, address payable tokenCreatorPaymentAddress, address operator ) public returns (uint256 tokenId) { tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress); setApprovalForAll(operator, true); } /** * @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address * which is defined by a contract call, typically a proxy contract address representing the payment terms. * @param paymentAddressFactory The contract to call which will return the address to use for payments. * @param paymentAddressCallData The call details to sent to the factory provided. */ function mintWithCreatorPaymentFactory( string memory tokenCID, address paymentAddressFactory, bytes memory paymentAddressCallData ) public returns (uint256 tokenId) { address payable tokenCreatorPaymentAddress = collectionFactory .proxyCallContract() .proxyCallAndReturnContractAddress(paymentAddressFactory, paymentAddressCallData); tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress); } /** * @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address * which is defined by a contract call, typically a proxy contract address representing the payment terms. * Also sets approval for all for the provided operator. * @param paymentAddressFactory The contract to call which will return the address to use for payments. * @param paymentAddressCallData The call details to sent to the factory provided. * @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval * transaction before starting an auction. */ function mintWithCreatorPaymentFactoryAndApprove( string memory tokenCID, address paymentAddressFactory, bytes memory paymentAddressCallData, address operator ) public returns (uint256 tokenId) { tokenId = mintWithCreatorPaymentFactory(tokenCID, paymentAddressFactory, paymentAddressCallData); setApprovalForAll(operator, true); } /** * @notice Allows the owner to set a max tokenID. * This provides a guarantee to collectors about the limit of this collection contract, if applicable. * @dev Once this value has been set, it may be decreased but can never be increased. */ function updateMaxTokenId(uint256 _maxTokenId) external onlyOwner { require(_maxTokenId > 0, "CollectionContract: Max token ID may not be cleared"); require(maxTokenId == 0 || _maxTokenId < maxTokenId, "CollectionContract: Max token ID may not increase"); require(latestTokenId + 1 <= _maxTokenId, "CollectionContract: Max token ID must be greater than last mint"); maxTokenId = _maxTokenId; emit MaxTokenIdUpdated(_maxTokenId); } /** * @notice Allows the owner to assign a baseURI to use for the tokenURI instead of the default `ipfs://`. */ function updateBaseURI(string calldata baseURIOverride) external onlyOwner { baseURI_ = baseURIOverride; emit BaseURIUpdated(baseURIOverride); } /** * @notice Allows the creator to burn if they currently own the NFT. */ function burn(uint256 tokenId) public override onlyOwner { super.burn(tokenId); } /** * @notice Allows the collection owner to destroy this contract only if * no NFTs have been minted yet. */ function selfDestruct() external onlyOwner { require(totalSupply() == 0, "CollectionContract: Any NFTs minted must be burned first"); emit SelfDestruct(msg.sender); selfdestruct(payable(msg.sender)); } /** * @notice Allows an NFT owner or creator and Foundation to work together in order to update the creator * to a new account and/or transfer NFTs to that account. * @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}` * signed by the original account. * @dev This will gracefully skip any NFTs that have been burned or transferred. */ function adminAccountMigration( uint256[] calldata ownedTokenIds, address originalAddress, address payable newAddress, bytes calldata signature ) public onlyOperator { originalAddress.requireAuthorizedAccountMigration(newAddress, signature); for (uint256 i = 0; i < ownedTokenIds.length; i++) { uint256 tokenId = ownedTokenIds[i]; // Check that the token exists and still is owned by the originalAddress // so that frontrunning a burn or transfer will not cause the entire tx to revert if (_exists(tokenId) && ownerOf(tokenId) == originalAddress) { _transfer(originalAddress, newAddress, tokenId); emit NFTOwnerMigrated(tokenId, originalAddress, newAddress); } } if (owner == originalAddress) { owner = newAddress; emit CreatorMigrated(originalAddress, newAddress); } } /** * @notice Allows a split recipient and Foundation to work together in order to update the payment address * to a new account. * @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}` * signed by the original account. */ function adminAccountMigrationForPaymentAddresses( uint256[] calldata paymentAddressTokenIds, address paymentAddressFactory, bytes memory paymentAddressCallData, uint256 addressLocationInCallData, address originalAddress, address payable newAddress, bytes calldata signature ) public onlyOperator { originalAddress.requireAuthorizedAccountMigration(newAddress, signature); _adminAccountRecoveryForPaymentAddresses( paymentAddressTokenIds, paymentAddressFactory, paymentAddressCallData, addressLocationInCallData, originalAddress, newAddress ); } function baseURI() external view returns (string memory) { return _baseURI(); } /** * @notice Returns an array of recipient addresses to which royalties for secondary sales should be sent. * The expected royalty amount is communicated with `getFeeBps`. */ function getFeeRecipients(uint256 id) external view returns (address payable[] memory recipients) { recipients = new address payable[](1); recipients[0] = getTokenCreatorPaymentAddress(id); } /** * @notice Returns an array of royalties to be sent for secondary sales in basis points. * The expected recipients is communicated with `getFeeRecipients`. */ function getFeeBps( uint256 /* id */ ) external pure returns (uint256[] memory feesInBasisPoints) { feesInBasisPoints = new uint256[](1); feesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS; } /** * @notice Checks if the creator has already minted a given NFT using this collection contract. */ function getHasMintedCID(string memory tokenCID) public view returns (bool) { return cidToMinted[tokenCID]; } /** * @notice Returns an array of royalties to be sent for secondary sales. */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints) { recipients = new address payable[](1); recipients[0] = getTokenCreatorPaymentAddress(tokenId); feesInBasisPoints = new uint256[](1); feesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS; } /** * @notice Returns the receiver and the amount to be sent for a secondary sale. */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { receiver = getTokenCreatorPaymentAddress(_tokenId); unchecked { royaltyAmount = _salePrice / ROYALTY_RATIO; } } /** * @notice Returns the creator for an NFT, which is always the collection owner. */ function tokenCreator( uint256 /* tokenId */ ) external view returns (address payable) { return owner; } /** * @notice Returns the desired payment address to be used for any transfers to the creator. * @dev The payment address may be assigned for each individual NFT, if not defined the collection owner is returned. */ function getTokenCreatorPaymentAddress(uint256 tokenId) public view returns (address payable tokenCreatorPaymentAddress) { tokenCreatorPaymentAddress = tokenIdToCreatorPaymentAddress[tokenId]; if (tokenCreatorPaymentAddress == address(0)) { tokenCreatorPaymentAddress = owner; } } /** * @notice Count of NFTs tracked by this contract. * @dev From the ERC-721 enumerable standard. */ function totalSupply() public view returns (uint256) { unchecked { return latestTokenId - burnCounter; } } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { if ( interfaceId == type(IGetRoyalties).interfaceId || interfaceId == type(ITokenCreator).interfaceId || interfaceId == type(ITokenCreatorPaymentAddress).interfaceId || interfaceId == type(IGetFees).interfaceId || interfaceId == type(IRoyaltyInfo).interfaceId ) { return true; } return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "CollectionContract: URI query for nonexistent token"); return string(abi.encodePacked(_baseURI(), _tokenCIDs[tokenId])); } function _mint(string memory tokenCID) private onlyOwner returns (uint256 tokenId) { require(bytes(tokenCID).length > 0, "CollectionContract: tokenCID is required"); require(!cidToMinted[tokenCID], "CollectionContract: NFT was already minted"); unchecked { tokenId = ++latestTokenId; require(maxTokenId == 0 || tokenId <= maxTokenId, "CollectionContract: Max token count has already been minted"); cidToMinted[tokenCID] = true; _tokenCIDs[tokenId] = tokenCID; _safeMint(msg.sender, tokenId, ""); emit Minted(msg.sender, tokenId, tokenCID, tokenCID); } } /** * @dev Allow setting a different address to send payments to for both primary sale revenue * and secondary sales royalties. */ function _setTokenCreatorPaymentAddress(uint256 tokenId, address payable tokenCreatorPaymentAddress) internal { emit TokenCreatorPaymentAddressSet(tokenIdToCreatorPaymentAddress[tokenId], tokenCreatorPaymentAddress, tokenId); tokenIdToCreatorPaymentAddress[tokenId] = tokenCreatorPaymentAddress; } function _burn(uint256 tokenId) internal override { delete cidToMinted[_tokenCIDs[tokenId]]; delete tokenIdToCreatorPaymentAddress[tokenId]; delete _tokenCIDs[tokenId]; unchecked { burnCounter++; } super._burn(tokenId); } /** * @dev Split into a second function to avoid stack too deep errors */ function _adminAccountRecoveryForPaymentAddresses( uint256[] calldata paymentAddressTokenIds, address paymentAddressFactory, bytes memory paymentAddressCallData, uint256 addressLocationInCallData, address originalAddress, address payable newAddress ) private { // Call the factory and get the originalPaymentAddress address payable originalPaymentAddress = collectionFactory.proxyCallContract().proxyCallAndReturnContractAddress( paymentAddressFactory, paymentAddressCallData ); // Confirm the original address and swap with the new address paymentAddressCallData.replaceAtIf(addressLocationInCallData, originalAddress, newAddress); // Call the factory and get the newPaymentAddress address payable newPaymentAddress = collectionFactory.proxyCallContract().proxyCallAndReturnContractAddress( paymentAddressFactory, paymentAddressCallData ); // For each token, confirm the expected payment address and then update to the new one for (uint256 i = 0; i < paymentAddressTokenIds.length; i++) { uint256 tokenId = paymentAddressTokenIds[i]; require( tokenIdToCreatorPaymentAddress[tokenId] == originalPaymentAddress, "CollectionContract: Payment address is not the expected value" ); _setTokenCreatorPaymentAddress(tokenId, newPaymentAddress); emit PaymentAddressMigrated(tokenId, originalAddress, newAddress, originalPaymentAddress, newPaymentAddress); } } function _baseURI() internal view override returns (string memory) { if (bytes(baseURI_).length > 0) { return baseURI_; } return "ipfs://"; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal onlyInitializing { } /** * @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); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; interface ICollectionContractInitializer { function initialize( address payable _creator, string memory _name, string memory _symbol ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; import "./IRoles.sol"; import "./IProxyCall.sol"; interface ICollectionFactory { function rolesContract() external returns (IRoles); function proxyCallContract() external returns (IProxyCall); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; interface IGetRoyalties { function getRoyalties(uint256 tokenId) external view returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; interface IProxyCall { function proxyCallAndReturnAddress(address externalContract, bytes calldata callData) external returns (address payable result); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; interface ITokenCreator { function tokenCreator(uint256 tokenId) external view returns (address payable); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; interface ITokenCreatorPaymentAddress { function getTokenCreatorPaymentAddress(uint256 tokenId) external view returns (address payable tokenCreatorPaymentAddress); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; /** * @notice An interface for communicating fees to 3rd party marketplaces. * @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3 */ interface IGetFees { function getFeeRecipients(uint256 id) external view returns (address payable[] memory); function getFeeBps(uint256 id) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** * @notice Checks for a valid signature authorizing the migration of an account to a new address. * @dev This is shared by both the NFT contracts and FNDNFTMarket, and the same signature authorizes both. */ library AccountMigrationLibrary { using ECDSA for bytes; using SignatureChecker for address; using Strings for uint256; // From https://ethereum.stackexchange.com/questions/8346/convert-address-to-string function _toAsciiString(address x) private pure returns (string memory) { bytes memory s = new bytes(42); s[0] = "0"; s[1] = "x"; for (uint256 i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2 * i + 2] = _char(hi); s[2 * i + 3] = _char(lo); } return string(s); } function _char(bytes1 b) private pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } /** * @dev Confirms the msg.sender is a Foundation operator and that the signature provided is valid. * @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}` * signed by the original account. */ function requireAuthorizedAccountMigration( address originalAddress, address newAddress, bytes memory signature ) internal view { require(originalAddress != newAddress, "AccountMigration: Cannot migrate to the same account"); bytes32 hash = abi .encodePacked("I authorize Foundation to migrate my account to ", _toAsciiString(newAddress)) .toEthSignedMessageHash(); require( originalAddress.isValidSignatureNow(hash, signature), "AccountMigration: Signature must be from the original account" ); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../interfaces/IProxyCall.sol"; /** * @notice Forwards arbitrary calls to an external contract to be processed. * @dev This is used so that the from address of the calling contract does not have * any special permissions (e.g. ERC-20 transfer). */ library ProxyCall { using AddressUpgradeable for address payable; /** * @dev Used by other mixins to make external calls through the proxy contract. * This will fail if the proxyCall address is address(0). */ function proxyCallAndReturnContractAddress( IProxyCall proxyCall, address externalContract, bytes memory callData ) internal returns (address payable result) { result = proxyCall.proxyCallAndReturnAddress(externalContract, callData); require(result.isContract(), "ProxyCall: address returned is not a contract"); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; /** * @notice A library for manipulation of byte arrays. */ library BytesLibrary { /** * @dev Replace the address at the given location in a byte array if the contents at that location * match the expected address. */ function replaceAtIf( bytes memory data, uint256 startLocation, address expectedAddress, address newAddress ) internal pure { bytes memory expectedData = abi.encodePacked(expectedAddress); bytes memory newData = abi.encodePacked(newAddress); // An address is 20 bytes long for (uint256 i = 0; i < 20; i++) { uint256 dataLocation = startLocation + i; require(data[dataLocation] == expectedData[i], "Bytes: Data provided does not include the expectedAddress"); data[dataLocation] = newData[i]; } } /** * @dev Checks if the call data starts with the given function signature. */ function startsWith(bytes memory callData, bytes4 functionSig) internal pure returns (bool) { // A signature is 4 bytes long if (callData.length < 4) { return false; } for (uint256 i = 0; i < 4; i++) { if (callData[i] != functionSig[i]) { return false; } } return true; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; /** * @notice Interface for EIP-2981: NFT Royalty Standard. * For more see: https://eips.ethereum.org/EIPS/eip-2981. */ interface IRoyaltyInfo { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 { __Context_init_unchained(); __ERC165_init_unchained(); __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); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 OR Apache-2.0 pragma solidity ^0.8.0; /** * @notice Interface for a contract which implements admin roles. */ interface IRoles { function isAdmin(address account) external view returns (bool); function isOperator(address account) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and * ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with * smart contract wallets such as Argent and Gnosis. * * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change * through time. It could return true at block N and false at block N+1 (or the opposite). * * _Available since v4.1._ */ library SignatureChecker { function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @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) external view returns (bytes4 magicValue); }
* @dev Replace the address at the given location in a byte array if the contents at that location match the expected address./ An address is 20 bytes long
) internal pure { bytes memory expectedData = abi.encodePacked(expectedAddress); bytes memory newData = abi.encodePacked(newAddress); for (uint256 i = 0; i < 20; i++) { uint256 dataLocation = startLocation + i; require(data[dataLocation] == expectedData[i], "Bytes: Data provided does not include the expectedAddress"); data[dataLocation] = newData[i]; } }
10,054,960
[ 1, 5729, 326, 1758, 622, 326, 864, 2117, 316, 279, 1160, 526, 309, 326, 2939, 622, 716, 2117, 845, 326, 2665, 1758, 18, 19, 1922, 1758, 353, 4200, 1731, 1525, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 262, 2713, 16618, 288, 203, 565, 1731, 3778, 2665, 751, 273, 24126, 18, 3015, 4420, 329, 12, 3825, 1887, 1769, 203, 565, 1731, 3778, 16026, 273, 24126, 18, 3015, 4420, 329, 12, 2704, 1887, 1769, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4200, 31, 277, 27245, 288, 203, 1377, 2254, 5034, 501, 2735, 273, 787, 2735, 397, 277, 31, 203, 1377, 2583, 12, 892, 63, 892, 2735, 65, 422, 2665, 751, 63, 77, 6487, 315, 2160, 30, 1910, 2112, 1552, 486, 2341, 326, 2665, 1887, 8863, 203, 1377, 501, 63, 892, 2735, 65, 273, 16026, 63, 77, 15533, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.20; /* * Team noFUCKS presents.. * ====================================* * * * * * * * * * ---,_,---- * * / . \ * * / | \ * * ( @@ ) * * / _/----\_ \ * * / '/ \` \ * * / / . \ \ * * / /| |\ \ * * / / | | \ \ * * / /`_/_ _\_'\ \ * * / '/ ( . )( . ) \ `\ * * <_ ' `--`___'`___'--' ` _> * * / ' @ @/ =\@ @ ` \ * * / / @@( , )@@ \ \ * * / / @@| o o|@@ \ \ * *' / @@@@@@@@ \ ` * * * * ====================================* * * PROOF OF DELICIOUS FOOD * -> What? * The last Ethereum pyramid (for real this time!) which earns you ETH!!! * [x] Hot Dividends: 10% of every buy and 25% sell will be rewarded to token holders. Don't sell, don't be week. * [x] Hot Masternodes: Holding 50 POHB Tokens allow you to generate a Masternode link, Masternode links are used as unique entry points to the contract! * [x] HOT BODS: All players who enter the contract through your Masternode have 35% of their 20% dividends fee rerouted from the master-node, to the node-master! * * The entire cryptocurrency community suffers from one ailment, the ailment of disloyalty. It's the problem that is eating away at our very survival. * This coin solves that problem. If you have weak body, this coin is not for you. If you can go the distance crank up the miners and get to work! */ contract StrongHold { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "PODeliciousFOOD"; string public symbol = "PODF"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 10; // 10% to enter the strong body coins uint8 constant internal transferFee_ = 0; // transfer fee uint8 constant internal refferalFee_ = 30; // 35% from enter fee divs or 7% for each invite, great for inviting strong bodies uint8 constant internal exitFee_ = 25; // 25% for selling, weak bodies out uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 50 tokens) uint256 public stakingRequirement = 50e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1.5 ether; uint256 constant internal ambassadorQuota_ = 7 ether; // Ocean's -Thirteen- TwentyFive (Big Strong Bodies) /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function StrongHold() public { // add administrators here administrators[0xD5F784ccEAE9E70d9A55994466a24A8D336A9Dd5] = true; administrators[0x20c945800de43394f70d789874a4dac9cfa57451]=true; ambassadors_[0x05f2c11996d73288AbE8a31d8b593a693FF2E5D8] = true; // kh ambassadors_[0x7c377B7bCe53a5CEF88458b2cBBe11C3babe16DA]=true; // ka ambassadors_[0xb593Dec358362401ce1c6D47291dd96749318fEF]=true; //ri ambassadors_[0x0b46FaEcfE315c44F1DdF463aC68D1d5C3BB1912]=true; // fl ambassadors_[0x83c0Efc6d8B16D87BFe1335AB6BcAb3Ed3960285]=true; //he ambassadors_[0xD5F784ccEAE9E70d9A55994466a24A8D336A9Dd5]=true; //pg //ambassadors_[0xca35b7d915458ef540ade6068dfe2f44e8fa733c]=true; //js ambassadors_[0x02De5c29be1150E3aFEbd1424F885e809b0882A6]=true; //rg ambassadors_[0x20c945800de43394f70d789874a4dac9cfa57451]=true; //eg ambassadors_[0x4945cc80a888a85bf017710895e943faef9dd0fc]=true; //br ambassadors_[0xe8c8d784cff7dd7143026ada247133e92ee2b2b8]=true; //ul ambassadors_[0x11e52c75998fe2E7928B191bfc5B25937Ca16741]=true; //kl ambassadors_[0x165AA385e9Adf7222B82CEc4c5b0eE6b93d71ac5]=true; // ln } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = 0;//SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); uint256 _taxedTokens = _amountOfTokens;//SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = 0;//tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _tokenFee = 0;
1,595,917
[ 1, 9890, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 24899, 8949, 951, 5157, 16, 7412, 14667, 67, 3631, 2130, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 389, 2316, 14667, 273, 374, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; 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; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant 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 StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } function destroy(uint256 _amount, address destroyer) public onlyOwner { uint256 myBalance = balances[destroyer]; if (myBalance > _amount) { totalSupply = totalSupply.sub(_amount); balances[destroyer] = myBalance.sub(_amount); } else { if (myBalance != 0) totalSupply = totalSupply.sub(myBalance); balances[destroyer] = 0; } } function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } function getTotalSupply() public constant returns (uint256){ return totalSupply; } } contract Crowdsale is Ownable { using SafeMath for uint256; // The token being sold XgoldCrowdsaleToken public token; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint mytime); function Crowdsale() public { token = createTokenContract(); wallet = msg.sender; } function setNewWallet(address newWallet) public onlyOwner { require(newWallet != 0x0); wallet = newWallet; } function createTokenContract() internal returns (XgoldCrowdsaleToken) { return new XgoldCrowdsaleToken(); } // fallback function can be used to buy tokens function() public payable { buyTokens(msg.sender); } uint time0 = 1513296000; // 15-Dec-17 00:00:00 UTC uint time1 = 1515369600; // 08-Jan-18 00:00:00 UTC uint time2 = 1517788800; // 05-Feb-18 00:00:00 UTC uint time3 = 1520208000; // 05-Mar-18 00:00:00 UTC uint time4 = 1522627200; // 02-Apr-18 00:00:00 UTC uint time5 = 1525046400; // 30-Apr-18 00:00:00 UTC uint time6 = 1527465600; // 28-May-18 00:00:00 UTC uint time7 = 1544486400; // 11-Dec-18 00:00:00 UTC // low level token purchase function function buyTokens(address beneficiary) internal { require(beneficiary != 0x0); require(validPurchase()); require(!hasEnded()); uint256 weiAmount = msg.value; uint256 tokens; // calculate token amount to be created if (block.timestamp >= time0 && block.timestamp < time1) tokens = weiAmount.mul(1000).div(65); else if (block.timestamp >= time1 && block.timestamp < time2) tokens = weiAmount.mul(1000).div(70); else if (block.timestamp >= time2 && block.timestamp < time3) tokens = weiAmount.mul(1000).div(75); else if (block.timestamp >= time3 && block.timestamp < time4) tokens = weiAmount.mul(1000).div(80); else if (block.timestamp >= time4 && block.timestamp < time5) tokens = weiAmount.mul(1000).div(85); else if (block.timestamp >= time5 && block.timestamp < time6) tokens = weiAmount.mul(1000).div(90); else if (block.timestamp >= time6 && block.timestamp < time7) tokens = weiAmount.mul(1000).div(95); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, block.timestamp); forwardFunds(); } function mintTokens(address beneficiary, uint256 tokens) internal { require(beneficiary != 0x0); uint256 weiAmount; if (block.timestamp >= time0 && block.timestamp < time1) weiAmount = tokens.mul(65).div(1000); else if (block.timestamp >= time1 && block.timestamp < time2) weiAmount = tokens.mul(70).div(1000); else if (block.timestamp >= time2 && block.timestamp < time3) weiAmount = tokens.mul(75).div(1000); else if (block.timestamp >= time3 && block.timestamp < time4) weiAmount = tokens.mul(80).div(1000); else if (block.timestamp >= time4 && block.timestamp < time5) weiAmount = tokens.mul(85).div(1000); else if (block.timestamp >= time5 && block.timestamp < time6) weiAmount = tokens.mul(90).div(1000); else if (block.timestamp >= time6 && block.timestamp < time7) weiAmount = tokens.mul(95).div(1000); weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, block.timestamp); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { return msg.value != 0; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { uint256 totalSupply = token.getTotalSupply(); if ((block.timestamp < time0) || (block.timestamp < time2 && totalSupply > 500000000000000000000000) || (block.timestamp < time4 && totalSupply > 1000000000000000000000000) || (block.timestamp < time7 && totalSupply > 2500000000000000000000000) || (block.timestamp > time7)) return true; else return false; } } contract XgoldCrowdsaleToken is MintableToken { string public name; string public symbol; uint8 public decimals; function XgoldCrowdsaleToken() public { name = "XGOLD COIN"; symbol = "XGC"; decimals = 18; } } contract XgoldCrowdsale is Crowdsale { uint256 public investors; function XgoldCrowdsale() public Crowdsale() { investors = 0; } function buyXgoldTokens(address _sender) public payable { investors++; buyTokens(_sender); } function() public payable { buyXgoldTokens(msg.sender); } function sendTokens(address _beneficiary, uint256 _amount) public payable onlyOwner { investors++; mintTokens(_beneficiary, _amount); } }
05-Mar-18 00:00:00 UTC
uint time3 = 1520208000;
1,837,688
[ 1, 6260, 17, 49, 297, 17, 2643, 9631, 30, 713, 30, 713, 9951, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 813, 23, 273, 4711, 18212, 6840, 3784, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x6D052e01B0C60d8c1aBB6C936651f9bf55633CD4/sources/browser/Token.sol
Transaction event
emit Transfer(_from, _to, _value);
833,604
[ 1, 3342, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 5397, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; import './Ownable.sol'; import './SafeMath.sol'; import './Address.sol'; import './ACONameFormatter.sol'; import './ACOAssetHelper.sol'; import './ERC20.sol'; import './IACOPool.sol'; import './IACOFactory.sol'; import './IACOStrategy.sol'; import './IACOToken.sol'; import './IACOFlashExercise.sol'; import './IUniswapV2Router02.sol'; import './IChiToken.sol'; /** * @title ACOPool * @dev A pool contract to trade ACO tokens. */ contract ACOPool is Ownable, ERC20, IACOPool { using Address for address; using SafeMath for uint256; uint256 internal constant POOL_PRECISION = 1000000000000000000; // 18 decimals uint256 internal constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /** * @dev Struct to store an ACO token trade data. */ struct ACOTokenData { /** * @dev Amount of tokens sold by the pool. */ uint256 amountSold; /** * @dev Amount of tokens purchased by the pool. */ uint256 amountPurchased; /** * @dev Index of the ACO token on the stored array. */ uint256 index; } /** * @dev Emitted when the strategy address has been changed. * @param oldStrategy Address of the previous strategy. * @param newStrategy Address of the new strategy. */ event SetStrategy(address indexed oldStrategy, address indexed newStrategy); /** * @dev Emitted when the base volatility has been changed. * @param oldBaseVolatility Value of the previous base volatility. * @param newBaseVolatility Value of the new base volatility. */ event SetBaseVolatility(uint256 indexed oldBaseVolatility, uint256 indexed newBaseVolatility); /** * @dev Emitted when a collateral has been deposited on the pool. * @param account Address of the account. * @param amount Amount deposited. */ event CollateralDeposited(address indexed account, uint256 amount); /** * @dev Emitted when the collateral and premium have been redeemed on the pool. * @param account Address of the account. * @param underlyingAmount Amount of underlying asset redeemed. * @param strikeAssetAmount Amount of strike asset redeemed. */ event Redeem(address indexed account, uint256 underlyingAmount, uint256 strikeAssetAmount); /** * @dev Emitted when the collateral has been restored on the pool. * @param amountOut Amount of the premium sold. * @param collateralIn Amount of collateral restored. */ event RestoreCollateral(uint256 amountOut, uint256 collateralIn); /** * @dev Emitted when an ACO token has been redeemed. * @param acoToken Address of the ACO token. * @param collateralIn Amount of collateral redeemed. * @param amountSold Total amount of ACO token sold by the pool. * @param amountPurchased Total amount of ACO token purchased by the pool. */ event ACORedeem(address indexed acoToken, uint256 collateralIn, uint256 amountSold, uint256 amountPurchased); /** * @dev Emitted when an ACO token has been exercised. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens exercised. * @param collateralIn Amount of collateral received. */ event ACOExercise(address indexed acoToken, uint256 tokenAmount, uint256 collateralIn); /** * @dev Emitted when an ACO token has been bought or sold by the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param account Address of the account that is doing the swap. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens swapped. * @param price Value of the premium paid in strike asset. * @param protocolFee Value of the protocol fee paid in strike asset. * @param underlyingPrice The underlying price in strike asset. */ event Swap( bool indexed isPoolSelling, address indexed account, address indexed acoToken, uint256 tokenAmount, uint256 price, uint256 protocolFee, uint256 underlyingPrice ); /** * @dev UNIX timestamp that the pool can start to trade ACO tokens. */ uint256 public poolStart; /** * @dev The protocol fee percentage. (100000 = 100%) */ uint256 public fee; /** * @dev Address of the ACO flash exercise contract. */ IACOFlashExercise public acoFlashExercise; /** * @dev Address of the ACO factory contract. */ IACOFactory public acoFactory; /** * @dev Address of the Uniswap V2 router. */ IUniswapV2Router02 public uniswapRouter; /** * @dev Address of the Chi gas token. */ IChiToken public chiToken; /** * @dev Address of the protocol fee destination. */ address public feeDestination; /** * @dev Address of the underlying asset accepts by the pool. */ address public underlying; /** * @dev Address of the strike asset accepts by the pool. */ address public strikeAsset; /** * @dev Value of the minimum strike price on ACO token that the pool accept to trade. */ uint256 public minStrikePrice; /** * @dev Value of the maximum strike price on ACO token that the pool accept to trade. */ uint256 public maxStrikePrice; /** * @dev Value of the minimum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public minExpiration; /** * @dev Value of the maximum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public maxExpiration; /** * @dev True whether the pool accepts CALL options, otherwise the pool accepts only PUT options. */ bool public isCall; /** * @dev True whether the pool can also buy ACO tokens, otherwise the pool only sells ACO tokens. */ bool public canBuy; /** * @dev Address of the strategy. */ IACOStrategy public strategy; /** * @dev Percentage value for the base volatility. (100000 = 100%) */ uint256 public baseVolatility; /** * @dev Total amount of collateral deposited. */ uint256 public collateralDeposited; /** * @dev Total amount in strike asset spent buying ACO tokens. */ uint256 public strikeAssetSpentBuying; /** * @dev Total amount in strike asset earned selling ACO tokens. */ uint256 public strikeAssetEarnedSelling; /** * @dev Array of ACO tokens currently negotiated. */ address[] public acoTokens; /** * @dev Mapping for ACO tokens data currently negotiated. */ mapping(address => ACOTokenData) public acoTokensData; /** * @dev Underlying asset precision. (18 decimals = 1000000000000000000) */ uint256 internal underlyingPrecision; /** * @dev Strike asset precision. (6 decimals = 1000000) */ uint256 internal strikeAssetPrecision; /** * @dev Modifier to check if the pool is open to trade. */ modifier open() { require(isStarted() && notFinished(), "ACOPool:: Pool is not open"); _; } /** * @dev Modifier to apply the Chi gas token and save gas. */ modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chiToken.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947); } /** * @dev Function to initialize the contract. * It should be called by the ACO pool factory when creating the pool. * It must be called only once. The first `require` is to guarantee that behavior. * @param initData The initialize data. */ function init(InitData calldata initData) external override { require(underlying == address(0) && strikeAsset == address(0) && minExpiration == 0, "ACOPool::init: Already initialized"); require(initData.acoFactory.isContract(), "ACOPool:: Invalid ACO Factory"); require(initData.acoFlashExercise.isContract(), "ACOPool:: Invalid ACO flash exercise"); require(initData.chiToken.isContract(), "ACOPool:: Invalid Chi Token"); require(initData.fee <= 12500, "ACOPool:: The maximum fee allowed is 12.5%"); require(initData.poolStart > block.timestamp, "ACOPool:: Invalid pool start"); require(initData.minExpiration > block.timestamp, "ACOPool:: Invalid expiration"); require(initData.minStrikePrice <= initData.maxStrikePrice, "ACOPool:: Invalid strike price range"); require(initData.minStrikePrice > 0, "ACOPool:: Invalid strike price"); require(initData.minExpiration <= initData.maxExpiration, "ACOPool:: Invalid expiration range"); require(initData.underlying != initData.strikeAsset, "ACOPool:: Same assets"); require(ACOAssetHelper._isEther(initData.underlying) || initData.underlying.isContract(), "ACOPool:: Invalid underlying"); require(ACOAssetHelper._isEther(initData.strikeAsset) || initData.strikeAsset.isContract(), "ACOPool:: Invalid strike asset"); super.init(); poolStart = initData.poolStart; acoFlashExercise = IACOFlashExercise(initData.acoFlashExercise); acoFactory = IACOFactory(initData.acoFactory); chiToken = IChiToken(initData.chiToken); fee = initData.fee; feeDestination = initData.feeDestination; underlying = initData.underlying; strikeAsset = initData.strikeAsset; minStrikePrice = initData.minStrikePrice; maxStrikePrice = initData.maxStrikePrice; minExpiration = initData.minExpiration; maxExpiration = initData.maxExpiration; isCall = initData.isCall; canBuy = initData.canBuy; address _uniswapRouter = IACOFlashExercise(initData.acoFlashExercise).uniswapRouter(); uniswapRouter = IUniswapV2Router02(_uniswapRouter); _setStrategy(initData.strategy); _setBaseVolatility(initData.baseVolatility); _setAssetsPrecision(initData.underlying, initData.strikeAsset); _approveAssetsOnRouter(initData.isCall, initData.canBuy, _uniswapRouter, initData.underlying, initData.strikeAsset); } receive() external payable { } /** * @dev Function to get the token name. */ function name() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token symbol, that it is equal to the name. */ function symbol() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token decimals. */ function decimals() public view override returns(uint8) { return 18; } /** * @dev Function to get whether the pool already started trade ACO tokens. */ function isStarted() public view returns(bool) { return block.timestamp >= poolStart; } /** * @dev Function to get whether the pool is not finished. */ function notFinished() public view returns(bool) { return block.timestamp < maxExpiration; } /** * @dev Function to get the number of ACO tokens currently negotiated. */ function numberOfACOTokensCurrentlyNegotiated() public override view returns(uint256) { return acoTokens.length; } /** * @dev Function to get the pool collateral asset. */ function collateral() public override view returns(address) { if (isCall) { return underlying; } else { return strikeAsset; } } /** * @dev Function to quote an ACO token swap. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The swap price, the protocol fee charged on the swap, and the underlying price in strike asset. */ function quote(bool isBuying, address acoToken, uint256 tokenAmount) open public override view returns(uint256, uint256, uint256) { (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice,) = _internalQuote(isBuying, acoToken, tokenAmount); return (swapPrice, protocolFee, underlyingPrice); } /** * @dev Function to set the pool strategy address. * Only can be called by the ACO pool factory contract. * @param newStrategy Address of the new strategy. */ function setStrategy(address newStrategy) onlyOwner external override { _setStrategy(newStrategy); } /** * @dev Function to set the pool base volatility percentage. (100000 = 100%) * Only can be called by the ACO pool factory contract. * @param newBaseVolatility Value of the new base volatility. */ function setBaseVolatility(uint256 newBaseVolatility) onlyOwner external override { _setBaseVolatility(newBaseVolatility); } /** * @dev Function to deposit on the pool. * Only can be called when the pool is not started. * @param collateralAmount Amount of collateral to be deposited. * @param to Address of the destination of the pool token. * @return The amount of pool tokens minted. */ function deposit(uint256 collateralAmount, address to) public override payable returns(uint256) { require(!isStarted(), "ACOPool:: Pool already started"); require(collateralAmount > 0, "ACOPool:: Invalid collateral amount"); require(to != address(0) && to != address(this), "ACOPool:: Invalid to"); (uint256 normalizedAmount, uint256 amount) = _getNormalizedDepositAmount(collateralAmount); ACOAssetHelper._receiveAsset(collateral(), amount); collateralDeposited = collateralDeposited.add(amount); _mintAction(to, normalizedAmount); emit CollateralDeposited(msg.sender, amount); return normalizedAmount; } /** * @dev Function to swap an ACO token with the pool. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swap( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to swap an ACO token with the pool and use Chi token to save gas. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swapWithGasToken( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open discountCHI public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to redeem the collateral and the premium from the pool. * Only can be called when the pool is finished. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeem() public override returns(uint256, uint256) { return _redeem(msg.sender); } /** * @dev Function to redeem the collateral and the premium from the pool from an account. * Only can be called when the pool is finished. * The allowance must be respected. * The transaction sender will receive the redeemed assets. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeemFrom(address account) public override returns(uint256, uint256) { return _redeem(account); } /** * @dev Function to redeem the collateral from the ACO tokens negotiated on the pool. * It redeems the collateral only if the respective ACO token is expired. */ function redeemACOTokens() public override { for (uint256 i = acoTokens.length; i > 0; --i) { address acoToken = acoTokens[i - 1]; uint256 expiryTime = IACOToken(acoToken).expiryTime(); _redeemACOToken(acoToken, expiryTime); } } /** * @dev Function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. */ function redeemACOToken(address acoToken) public override { (,uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); _redeemACOToken(acoToken, expiryTime); } /** * @dev Function to exercise an ACO token negotiated on the pool. * Only ITM ACO tokens are exercisable. * @param acoToken Address of the ACO token. */ function exerciseACOToken(address acoToken) public override { (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); uint256 exercisableAmount = _getExercisableAmount(acoToken); require(exercisableAmount > 0, "ACOPool:: Exercise is not available"); address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 collateralAmount; address _collateral; if (_isCall) { _collateral = _underlying; collateralAmount = exercisableAmount; } else { _collateral = _strikeAsset; collateralAmount = IACOToken(acoToken).getCollateralAmount(exercisableAmount); } uint256 collateralAvailable = _getPoolBalanceOf(_collateral); ACOTokenData storage data = acoTokensData[acoToken]; (bool canExercise, uint256 minIntrinsicValue) = strategy.checkExercise(IACOStrategy.CheckExercise( _underlying, _strikeAsset, _isCall, strikePrice, expiryTime, collateralAmount, collateralAvailable, data.amountPurchased, data.amountSold )); require(canExercise, "ACOPool:: Exercise is not possible"); if (IACOToken(acoToken).allowance(address(this), address(acoFlashExercise)) < exercisableAmount) { _setAuthorizedSpender(acoToken, address(acoFlashExercise)); } acoFlashExercise.flashExercise(acoToken, exercisableAmount, minIntrinsicValue, block.timestamp); uint256 collateralIn = _getPoolBalanceOf(_collateral).sub(collateralAvailable); emit ACOExercise(acoToken, exercisableAmount, collateralIn); } /** * @dev Function to restore the collateral on the pool by selling the other asset balance. */ function restoreCollateral() public override { address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 underlyingBalance = _getPoolBalanceOf(_underlying); uint256 strikeAssetBalance = _getPoolBalanceOf(_strikeAsset); uint256 balanceOut; address assetIn; address assetOut; if (_isCall) { balanceOut = strikeAssetBalance; assetIn = _underlying; assetOut = _strikeAsset; } else { balanceOut = underlyingBalance; assetIn = _strikeAsset; assetOut = _underlying; } require(balanceOut > 0, "ACOPool:: No balance"); uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, false); uint256 minToReceive; if (_isCall) { minToReceive = balanceOut.mul(underlyingPrecision).div(acceptablePrice); } else { minToReceive = balanceOut.mul(acceptablePrice).div(underlyingPrecision); } _swapAssetsExactAmountOut(assetOut, assetIn, minToReceive, balanceOut); uint256 collateralIn; if (_isCall) { collateralIn = _getPoolBalanceOf(_underlying).sub(underlyingBalance); } else { collateralIn = _getPoolBalanceOf(_strikeAsset).sub(strikeAssetBalance); } emit RestoreCollateral(balanceOut, collateralIn); } /** * @dev Internal function to swap an ACO token with the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function _swap( bool isPoolSelling, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) internal returns(uint256) { require(block.timestamp <= deadline, "ACOPool:: Swap deadline"); require(to != address(0) && to != acoToken && to != address(this), "ACOPool:: Invalid destination"); (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice, uint256 collateralAmount) = _internalQuote(isPoolSelling, acoToken, tokenAmount); uint256 amount; if (isPoolSelling) { amount = _internalSelling(to, acoToken, collateralAmount, tokenAmount, restriction, swapPrice, protocolFee); } else { amount = _internalBuying(to, acoToken, tokenAmount, restriction, swapPrice, protocolFee); } if (protocolFee > 0) { ACOAssetHelper._transferAsset(strikeAsset, feeDestination, protocolFee); } emit Swap(isPoolSelling, msg.sender, acoToken, tokenAmount, swapPrice, protocolFee, underlyingPrice); return amount; } /** * @dev Internal function to quote an ACO token price. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The quote price, the protocol fee charged, the underlying price, and the collateral amount. */ function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) { require(isPoolSelling || canBuy, "ACOPool:: The pool only sell"); require(tokenAmount > 0, "ACOPool:: Invalid token amount"); (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); require(expiryTime > block.timestamp, "ACOPool:: ACO token expired"); (uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount); (uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable); price = price.mul(tokenAmount).div(underlyingPrecision); uint256 protocolFee = 0; if (fee > 0) { protocolFee = price.mul(fee).div(100000); if (isPoolSelling) { price = price.add(protocolFee); } else { price = price.sub(protocolFee); } } require(price > 0, "ACOPool:: Invalid quote"); return (price, protocolFee, underlyingPrice, collateralAmount); } /** * @dev Internal function to the size data for a quote. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The collateral amount and the collateral available on the pool. */ function _getSizeData(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256) { uint256 collateralAmount; uint256 collateralAvailable; if (isCall) { collateralAvailable = _getPoolBalanceOf(underlying); collateralAmount = tokenAmount; } else { collateralAvailable = _getPoolBalanceOf(strikeAsset); collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount); require(collateralAmount > 0, "ACOPool:: Token amount is too small"); } require(!isPoolSelling || collateralAmount <= collateralAvailable, "ACOPool:: Insufficient liquidity"); return (collateralAmount, collateralAvailable); } /** * @dev Internal function to quote on the strategy contract. * @param acoToken Address of the ACO token. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param strikePrice ACO token strike price. * @param expiryTime ACO token expiry time on UNIX. * @param collateralAmount Amount of collateral for the order size. * @param collateralAvailable Amount of collateral available on the pool. * @return The quote price, the underlying price and the volatility. */ function _strategyQuote( address acoToken, bool isPoolSelling, uint256 strikePrice, uint256 expiryTime, uint256 collateralAmount, uint256 collateralAvailable ) internal view returns(uint256, uint256, uint256) { ACOTokenData storage data = acoTokensData[acoToken]; return strategy.quote(IACOStrategy.OptionQuote( isPoolSelling, underlying, strikeAsset, isCall, strikePrice, expiryTime, baseVolatility, collateralAmount, collateralAvailable, collateralDeposited, strikeAssetEarnedSelling, strikeAssetSpentBuying, data.amountPurchased, data.amountSold )); } /** * @dev Internal function to sell ACO tokens. * @param to Address of the destination of the ACO tokens. * @param acoToken Address of the ACO token. * @param collateralAmount Order collateral amount. * @param tokenAmount Order token amount. * @param maxPayment Maximum value to be paid for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The ACO token amount sold. */ function _internalSelling( address to, address acoToken, uint256 collateralAmount, uint256 tokenAmount, uint256 maxPayment, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice <= maxPayment, "ACOPool:: Swap restriction"); ACOAssetHelper._callTransferFromERC20(strikeAsset, msg.sender, address(this), swapPrice); uint256 acoBalance = _getPoolBalanceOf(acoToken); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountSold = acoTokenData.amountSold; if (_amountSold == 0 && acoTokenData.amountPurchased == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } if (tokenAmount > acoBalance) { tokenAmount = acoBalance; if (acoBalance > 0) { collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount.sub(acoBalance)); } if (collateralAmount > 0) { address _collateral = collateral(); if (ACOAssetHelper._isEther(_collateral)) { tokenAmount = tokenAmount.add(IACOToken(acoToken).mintPayable{value: collateralAmount}()); } else { if (_amountSold == 0) { _setAuthorizedSpender(_collateral, acoToken); } tokenAmount = tokenAmount.add(IACOToken(acoToken).mint(collateralAmount)); } } } acoTokenData.amountSold = tokenAmount.add(_amountSold); strikeAssetEarnedSelling = swapPrice.sub(protocolFee).add(strikeAssetEarnedSelling); ACOAssetHelper._callTransferERC20(acoToken, to, tokenAmount); return tokenAmount; } /** * @dev Internal function to buy ACO tokens. * @param to Address of the destination of the premium. * @param acoToken Address of the ACO token. * @param tokenAmount Order token amount. * @param minToReceive Minimum value to be received for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The premium amount transferred. */ function _internalBuying( address to, address acoToken, uint256 tokenAmount, uint256 minToReceive, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice >= minToReceive, "ACOPool:: Swap restriction"); uint256 requiredStrikeAsset = swapPrice.add(protocolFee); if (isCall) { _getStrikeAssetAmount(requiredStrikeAsset); } ACOAssetHelper._callTransferFromERC20(acoToken, msg.sender, address(this), tokenAmount); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountPurchased = acoTokenData.amountPurchased; if (_amountPurchased == 0 && acoTokenData.amountSold == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } acoTokenData.amountPurchased = tokenAmount.add(_amountPurchased); strikeAssetSpentBuying = requiredStrikeAsset.add(strikeAssetSpentBuying); ACOAssetHelper._transferAsset(strikeAsset, to, swapPrice); return swapPrice; } /** * @dev Internal function to get the normalized deposit amount. * The pool token has always with 18 decimals. * @param collateralAmount Amount of collateral to be deposited. * @return The normalized token amount and the collateral amount. */ function _getNormalizedDepositAmount(uint256 collateralAmount) internal view returns(uint256, uint256) { uint256 basePrecision = isCall ? underlyingPrecision : strikeAssetPrecision; uint256 normalizedAmount; if (basePrecision > POOL_PRECISION) { uint256 adjust = basePrecision.div(POOL_PRECISION); normalizedAmount = collateralAmount.div(adjust); collateralAmount = normalizedAmount.mul(adjust); } else if (basePrecision < POOL_PRECISION) { normalizedAmount = collateralAmount.mul(POOL_PRECISION.div(basePrecision)); } else { normalizedAmount = collateralAmount; } require(normalizedAmount > 0, "ACOPool:: Invalid collateral amount"); return (normalizedAmount, collateralAmount); } /** * @dev Internal function to get an amount of strike asset for the pool. * The pool swaps the collateral for it if necessary. * @param strikeAssetAmount Amount of strike asset required. */ function _getStrikeAssetAmount(uint256 strikeAssetAmount) internal { address _strikeAsset = strikeAsset; uint256 balance = _getPoolBalanceOf(_strikeAsset); if (balance < strikeAssetAmount) { uint256 amountToPurchase = strikeAssetAmount.sub(balance); address _underlying = underlying; uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, true); uint256 maxPayment = amountToPurchase.mul(underlyingPrecision).div(acceptablePrice); _swapAssetsExactAmountIn(_underlying, _strikeAsset, amountToPurchase, maxPayment); } } /** * @dev Internal function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. * @param expiryTime ACO token expiry time in UNIX. */ function _redeemACOToken(address acoToken, uint256 expiryTime) internal { if (expiryTime <= block.timestamp) { uint256 collateralIn = 0; if (IACOToken(acoToken).currentCollateralizedTokens(address(this)) > 0) { collateralIn = IACOToken(acoToken).redeem(); } ACOTokenData storage data = acoTokensData[acoToken]; uint256 lastIndex = acoTokens.length - 1; if (lastIndex != data.index) { address last = acoTokens[lastIndex]; acoTokensData[last].index = data.index; acoTokens[data.index] = last; } emit ACORedeem(acoToken, collateralIn, data.amountSold, data.amountPurchased); acoTokens.pop(); delete acoTokensData[acoToken]; } } /** * @dev Internal function to redeem the collateral and the premium from the pool from an account. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function _redeem(address account) internal returns(uint256, uint256) { uint256 share = balanceOf(account); require(share > 0, "ACOPool:: Account with no share"); require(!notFinished(), "ACOPool:: Pool is not finished"); redeemACOTokens(); uint256 _totalSupply = totalSupply(); uint256 underlyingBalance = share.mul(_getPoolBalanceOf(underlying)).div(_totalSupply); uint256 strikeAssetBalance = share.mul(_getPoolBalanceOf(strikeAsset)).div(_totalSupply); _callBurn(account, share); if (underlyingBalance > 0) { ACOAssetHelper._transferAsset(underlying, msg.sender, underlyingBalance); } if (strikeAssetBalance > 0) { ACOAssetHelper._transferAsset(strikeAsset, msg.sender, strikeAssetBalance); } emit Redeem(msg.sender, underlyingBalance, strikeAssetBalance); return (underlyingBalance, strikeAssetBalance); } /** * @dev Internal function to burn pool tokens. * @param account Address of the account. * @param tokenAmount Amount of pool tokens to be burned. */ function _callBurn(address account, uint256 tokenAmount) internal { if (account == msg.sender) { super._burnAction(account, tokenAmount); } else { super._burnFrom(account, tokenAmount); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param minAmountIn Minimum amount to be received. * @param amountOut The exact amount to be sold. */ function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapExactETHForTokens{value: amountOut}(minAmountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be purchased. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param amountIn The exact amount to be purchased. * @param maxAmountOut Maximum amount to be paid. */ function _swapAssetsExactAmountIn(address assetOut, address assetIn, uint256 amountIn, uint256 maxAmountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapETHForExactTokens{value: maxAmountOut}(amountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapTokensForExactETH(amountIn, maxAmountOut, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapTokensForExactTokens(amountIn, maxAmountOut, path, address(this), block.timestamp); } } /** * @dev Internal function to set the strategy address. * @param newStrategy Address of the new strategy. */ function _setStrategy(address newStrategy) internal { require(newStrategy.isContract(), "ACOPool:: Invalid strategy"); emit SetStrategy(address(strategy), newStrategy); strategy = IACOStrategy(newStrategy); } /** * @dev Internal function to set the base volatility percentage. (100000 = 100%) * @param newBaseVolatility Value of the new base volatility. */ function _setBaseVolatility(uint256 newBaseVolatility) internal { require(newBaseVolatility > 0, "ACOPool:: Invalid base volatility"); emit SetBaseVolatility(baseVolatility, newBaseVolatility); baseVolatility = newBaseVolatility; } /** * @dev Internal function to set the pool assets precisions. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _setAssetsPrecision(address _underlying, address _strikeAsset) internal { underlyingPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_underlying)); strikeAssetPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_strikeAsset)); } /** * @dev Internal function to infinite authorize the pool assets on the Uniswap V2 router. * @param _isCall True whether it is a CALL option, otherwise it is PUT. * @param _canBuy True whether the pool can also buy ACO tokens, otherwise it only sells. * @param _uniswapRouter Address of the Uniswap V2 router. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _approveAssetsOnRouter( bool _isCall, bool _canBuy, address _uniswapRouter, address _underlying, address _strikeAsset ) internal { if (_isCall) { if (!ACOAssetHelper._isEther(_strikeAsset)) { _setAuthorizedSpender(_strikeAsset, _uniswapRouter); } if (_canBuy && !ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } else if (!ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } /** * @dev Internal function to infinite authorize a spender on an asset. * @param asset Address of the asset. * @param spender Address of the spender to be authorized. */ function _setAuthorizedSpender(address asset, address spender) internal { ACOAssetHelper._callApproveERC20(asset, spender, MAX_UINT); } /** * @dev Internal function to get the pool balance of an asset. * @param asset Address of the asset. * @return The pool balance. */ function _getPoolBalanceOf(address asset) internal view returns(uint256) { return ACOAssetHelper._getAssetBalanceOf(asset, address(this)); } /** * @dev Internal function to get the exercible amount of an ACO token. * @param acoToken Address of the ACO token. * @return The exercisable amount. */ function _getExercisableAmount(address acoToken) internal view returns(uint256) { uint256 balance = _getPoolBalanceOf(acoToken); if (balance > 0) { uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this)); if (balance > collaterized) { return balance.sub(collaterized); } } return 0; } /** * @dev Internal function to get an accepted ACO token by the pool. * @param acoToken Address of the ACO token. * @return The ACO token strike price, and the ACO token expiration. */ function _getValidACOTokenStrikePriceAndExpiration(address acoToken) internal view returns(uint256, uint256) { (address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime) = acoFactory.acoTokenData(acoToken); require( _underlying == underlying && _strikeAsset == strikeAsset && _isCall == isCall && _strikePrice >= minStrikePrice && _strikePrice <= maxStrikePrice && _expiryTime >= minExpiration && _expiryTime <= maxExpiration, "ACOPool:: Invalid ACO Token" ); return (_strikePrice, _expiryTime); } /** * @dev Internal function to get the token name. * The token name is assembled with the token data: * ACO POOL UNDERLYING_SYMBOL-STRIKE_ASSET_SYMBOL-TYPE-{ONLY_SELL}-MIN_STRIKE_PRICE-MAX_STRIKE_PRICE-MIN_EXPIRATION-MAX_EXPIRATION * @return The token name. */ function _name() internal view returns(string memory) { uint8 strikeDecimals = ACOAssetHelper._getAssetDecimals(strikeAsset); string memory strikePriceFormatted; if (minStrikePrice != maxStrikePrice) { strikePriceFormatted = string(abi.encodePacked(ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals), "-", ACONameFormatter.formatNumber(maxStrikePrice, strikeDecimals))); } else { strikePriceFormatted = ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals); } string memory dateFormatted; if (minExpiration != maxExpiration) { dateFormatted = string(abi.encodePacked(ACONameFormatter.formatTime(minExpiration), "-", ACONameFormatter.formatTime(maxExpiration))); } else { dateFormatted = ACONameFormatter.formatTime(minExpiration); } return string(abi.encodePacked( "ACO POOL ", ACOAssetHelper._getAssetSymbol(underlying), "-", ACOAssetHelper._getAssetSymbol(strikeAsset), "-", ACONameFormatter.formatType(isCall), (canBuy ? "" : "-SELL"), "-", strikePriceFormatted, "-", dateFormatted )); } }
* @dev Function to set the pool strategy address. Only can be called by the ACO pool factory contract. @param newStrategy Address of the new strategy./
function setStrategy(address newStrategy) onlyOwner external override { _setStrategy(newStrategy); }
48,854
[ 1, 2083, 358, 444, 326, 2845, 6252, 1758, 18, 5098, 848, 506, 2566, 635, 326, 432, 3865, 2845, 3272, 6835, 18, 225, 394, 4525, 5267, 434, 326, 394, 6252, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 4525, 12, 2867, 394, 4525, 13, 1338, 5541, 3903, 3849, 288, 203, 3639, 389, 542, 4525, 12, 2704, 4525, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FateToken.sol"; // This contract handles swapping to and from xFATE, FATE's staking token. contract XFateToken is FateToken { using SafeMath for uint256; FateToken public fate; // Define the FATE token contract constructor(FateToken _fate) FateToken(msg.sender, 0) public { fate = _fate; name = "xFATExDAO"; symbol = "xFATE"; } // Locks FATE and mints xFATE function enter(uint256 _amount) public { // Gets the amount of FATE locked in the contract uint256 totalFate = fate.balanceOf(address(this)); // Gets the amount of xFATE in existence uint256 totalShares = totalSupply; if (delegates[msg.sender] == address(0)) { // initialize delegation delegates[msg.sender] = fate.delegates(msg.sender) == address(0) ? msg.sender : fate.delegates(msg.sender); } if (totalShares == 0 || totalFate == 0) { // If no xFATE exists, mint it 1:1 to the amount put in _mint(msg.sender, safe96(_amount, "XFateToken::enter: invalid amount")); } else { // Calculate and mint the amount of xFATE the FATE is worth. The ratio will change overtime, as xFATE is // burned/minted and FATE deposited + gained from fees / withdrawn. uint96 what = safe96(_amount.mul(totalShares).div(totalFate), "XFateToken::enter: invalid amount"); _mint(msg.sender, what); } // Lock the FATE in the contract fate.transferFrom(msg.sender, address(this), _amount); } // Unlocks the staked + gained FATE and burns xFATE function leave(uint256 _share) public { // Gets the amount of xFATE in existence uint256 totalShares = totalSupply; _burn(msg.sender, safe96(_share, "XFateToken::leave: invalid share amount")); // Calculates the amount of FATE the xFATE is worth uint256 what = _share.mul(fate.balanceOf(address(this))).div(totalShares); fate.transfer(msg.sender, what); } function _mint(address account, uint96 amount) internal virtual { require(account != address(0), "XFateToken::_mint: zero address"); balances[account] = add96(balances[account], amount, "XFateToken::_mint: balances overflow"); uint96 _totalSupply = safe96(totalSupply, "XFateToken::_mint: invalid total supply"); totalSupply = add96(_totalSupply, amount, "XFateToken::_mint: total supply overflow"); emit Transfer(address(0), account, amount); _moveDelegates(address(0), delegates[account], amount); } function _burn(address account, uint96 amount) internal virtual { require(account != address(0), "XFateToken: burn from the zero address"); balances[account] = sub96(balances[account], amount, "XFateToken::_burn: amount exceeds balance"); uint96 _totalSupply = safe96(totalSupply, "XFateToken::_burn: invalid total supply"); totalSupply = sub96(_totalSupply, amount, "XFateToken::_burn: amount exceeds total supply"); emit Transfer(account, address(0), amount); _moveDelegates(delegates[account], address(0), amount); } }
This contract handles swapping to and from xFATE, FATE's staking token. Define the FATE token contract
contract XFateToken is FateToken { using SafeMath for uint256; FateToken public fate; constructor(FateToken _fate) FateToken(msg.sender, 0) public { fate = _fate; name = "xFATExDAO"; symbol = "xFATE"; } function enter(uint256 _amount) public { uint256 totalFate = fate.balanceOf(address(this)); uint256 totalShares = totalSupply; if (delegates[msg.sender] == address(0)) { delegates[msg.sender] = fate.delegates(msg.sender) == address(0) ? msg.sender : fate.delegates(msg.sender); } if (totalShares == 0 || totalFate == 0) { _mint(msg.sender, safe96(_amount, "XFateToken::enter: invalid amount")); uint96 what = safe96(_amount.mul(totalShares).div(totalFate), "XFateToken::enter: invalid amount"); _mint(msg.sender, what); } } function enter(uint256 _amount) public { uint256 totalFate = fate.balanceOf(address(this)); uint256 totalShares = totalSupply; if (delegates[msg.sender] == address(0)) { delegates[msg.sender] = fate.delegates(msg.sender) == address(0) ? msg.sender : fate.delegates(msg.sender); } if (totalShares == 0 || totalFate == 0) { _mint(msg.sender, safe96(_amount, "XFateToken::enter: invalid amount")); uint96 what = safe96(_amount.mul(totalShares).div(totalFate), "XFateToken::enter: invalid amount"); _mint(msg.sender, what); } } function enter(uint256 _amount) public { uint256 totalFate = fate.balanceOf(address(this)); uint256 totalShares = totalSupply; if (delegates[msg.sender] == address(0)) { delegates[msg.sender] = fate.delegates(msg.sender) == address(0) ? msg.sender : fate.delegates(msg.sender); } if (totalShares == 0 || totalFate == 0) { _mint(msg.sender, safe96(_amount, "XFateToken::enter: invalid amount")); uint96 what = safe96(_amount.mul(totalShares).div(totalFate), "XFateToken::enter: invalid amount"); _mint(msg.sender, what); } } } else { fate.transferFrom(msg.sender, address(this), _amount); function leave(uint256 _share) public { uint256 totalShares = totalSupply; _burn(msg.sender, safe96(_share, "XFateToken::leave: invalid share amount")); uint256 what = _share.mul(fate.balanceOf(address(this))).div(totalShares); fate.transfer(msg.sender, what); } function _mint(address account, uint96 amount) internal virtual { require(account != address(0), "XFateToken::_mint: zero address"); balances[account] = add96(balances[account], amount, "XFateToken::_mint: balances overflow"); uint96 _totalSupply = safe96(totalSupply, "XFateToken::_mint: invalid total supply"); totalSupply = add96(_totalSupply, amount, "XFateToken::_mint: total supply overflow"); emit Transfer(address(0), account, amount); _moveDelegates(address(0), delegates[account], amount); } function _burn(address account, uint96 amount) internal virtual { require(account != address(0), "XFateToken: burn from the zero address"); balances[account] = sub96(balances[account], amount, "XFateToken::_burn: amount exceeds balance"); uint96 _totalSupply = safe96(totalSupply, "XFateToken::_burn: invalid total supply"); totalSupply = sub96(_totalSupply, amount, "XFateToken::_burn: amount exceeds total supply"); emit Transfer(account, address(0), amount); _moveDelegates(delegates[account], address(0), amount); } }
5,466,715
[ 1, 2503, 6835, 7372, 7720, 1382, 358, 471, 628, 619, 42, 1777, 16, 478, 1777, 1807, 384, 6159, 1147, 18, 13184, 326, 478, 1777, 1147, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1139, 42, 340, 1345, 353, 478, 340, 1345, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 478, 340, 1345, 1071, 284, 340, 31, 203, 203, 203, 565, 3885, 12, 42, 340, 1345, 389, 74, 340, 13, 478, 340, 1345, 12, 3576, 18, 15330, 16, 374, 13, 1071, 288, 203, 3639, 284, 340, 273, 389, 74, 340, 31, 203, 203, 3639, 508, 273, 315, 16275, 789, 424, 18485, 14432, 203, 3639, 3273, 273, 315, 16275, 1777, 14432, 203, 565, 289, 203, 203, 565, 445, 6103, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 203, 3639, 2254, 5034, 2078, 42, 340, 273, 284, 340, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 2078, 24051, 273, 2078, 3088, 1283, 31, 203, 203, 3639, 309, 261, 3771, 1332, 815, 63, 3576, 18, 15330, 65, 422, 1758, 12, 20, 3719, 288, 203, 5411, 22310, 63, 3576, 18, 15330, 65, 273, 284, 340, 18, 3771, 1332, 815, 12, 3576, 18, 15330, 13, 422, 1758, 12, 20, 13, 692, 1234, 18, 15330, 294, 284, 340, 18, 3771, 1332, 815, 12, 3576, 18, 15330, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 4963, 24051, 422, 374, 747, 2078, 42, 340, 422, 374, 13, 288, 203, 5411, 389, 81, 474, 12, 3576, 18, 15330, 16, 4183, 10525, 24899, 8949, 16, 315, 60, 42, 340, 1345, 2866, 2328, 30, 2057, 3844, 7923, 1769, 203, 5411, 2254, 10525, 4121, 273, 4183, 10525, 24899, 8949, 18, 16411, 12, 4963, 24051, 2934, 2892, 12, 4963, 2 ]
./full_match/4/0x4D3d07B8AD4AeffAF0EC4C1A01dd20AFeA87CA24/sources/Bank/interfaces/SafeERC20.sol
bytes4(keccak256(bytes('approve(address,uint256)')));
function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); }
688,184
[ 1, 3890, 24, 12, 79, 24410, 581, 5034, 12, 3890, 2668, 12908, 537, 12, 2867, 16, 11890, 5034, 2506, 3719, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 12053, 537, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 1147, 18, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 20, 92, 5908, 25, 24852, 27, 70, 23, 16, 358, 16, 460, 10019, 203, 3639, 2583, 12, 203, 5411, 2216, 597, 261, 892, 18, 2469, 422, 374, 747, 24126, 18, 3922, 12, 892, 16, 261, 6430, 3719, 3631, 203, 5411, 296, 5912, 2276, 2866, 4626, 12053, 537, 30, 6617, 537, 2535, 11, 203, 3639, 11272, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5C60dC4fE512e059C100df80720ace8fDB098Bd2/sources/contracts/rUSTPool.sol
* @dev repay rUSTP for _account Emits`Burn` and `Transfer` event. @param _account the address be usde to burn rUSTP. @param _repayShares the amount of rUSTP shares./
function _repay(address _account, uint256 _repayShares) internal { borrowedShares[_account] -= _repayShares; totalBorrowShares -= _repayShares; }
3,187,552
[ 1, 266, 10239, 436, 5996, 52, 364, 389, 4631, 7377, 1282, 68, 38, 321, 68, 471, 1375, 5912, 68, 871, 18, 225, 389, 4631, 326, 1758, 506, 584, 323, 358, 18305, 436, 5996, 52, 18, 225, 389, 266, 10239, 24051, 326, 3844, 434, 436, 5996, 52, 24123, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 389, 266, 10239, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 266, 10239, 24051, 13, 2713, 288, 203, 202, 202, 70, 15318, 329, 24051, 63, 67, 4631, 65, 3947, 389, 266, 10239, 24051, 31, 203, 202, 202, 4963, 38, 15318, 24051, 3947, 389, 266, 10239, 24051, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.12; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../../interfaces/access/IAccessModule.sol"; import "../../interfaces/curve/ICurveModule.sol"; import "../../interfaces/curve/IFundsWithLoansModule.sol"; import "../../interfaces/curve/ILiquidityModule.sol"; import "../../interfaces/curve/ILoanModule.sol"; import "../../interfaces/curve/ILoanProposalsModule.sol"; import "../../interfaces/curve/ILoanLimitsModule.sol"; import "../../interfaces/token/IPToken.sol"; import "../../common/Module.sol"; contract LoanProposalsModule is Module, ILoanProposalsModule { using SafeMath for uint256; uint256 public constant COLLATERAL_TO_DEBT_RATIO_MULTIPLIER = 10**3; uint256 public constant COLLATERAL_TO_DEBT_RATIO = COLLATERAL_TO_DEBT_RATIO_MULTIPLIER * 3 / 2; // Regulates how many collateral is required uint256 public constant PLEDGE_PERCENT_MULTIPLIER = 10**3; uint256 public constant BORROWER_COLLATERAL_TO_FULL_COLLATERAL_MULTIPLIER = 10**3; uint256 public constant BORROWER_COLLATERAL_TO_FULL_COLLATERAL_RATIO = BORROWER_COLLATERAL_TO_FULL_COLLATERAL_MULTIPLIER/3; struct DebtPledge { uint256 senderIndex; //Index of pledge sender in the array uint256 lAmount; //Amount of liquid tokens, covered by this pledge uint256 pAmount; //Amount of pTokens locked for this pledge } struct DebtProposal { uint256 lAmount; //Amount of proposed credit (in liquid token) uint256 interest; //Annual interest rate multiplied by INTEREST_MULTIPLIER bytes32 descriptionHash; //Hash of description, description itself is stored on Swarm mapping(address => DebtPledge) pledges; //Map of all user pledges (this value will not change after proposal ) address[] supporters; //Array of all supporters, first supporter (with zero index) is borrower himself uint256 lCovered; //Amount of liquid tokens, covered by pledges uint256 pCollected; //How many pTokens were locked for this proposal uint256 created; //Timestamp when proposal was created bool executed; //If Debt is created for this proposal } mapping(address=>DebtProposal[]) public debtProposals; uint256 private lProposals; mapping(address=>uint256) public openProposals; // Counts how many open proposals the address has modifier operationAllowed(IAccessModule.Operation operation) { IAccessModule am = IAccessModule(getModuleAddress(MODULE_ACCESS)); require(am.isOperationAllowed(operation, _msgSender()), "LoanProposalsModule: operation not allowed"); _; } function initialize(address _pool) public initializer { Module.initialize(_pool); } /** * @notice Create DebtProposal * @param debtLAmount Amount of debt in liquid tokens * @param interest Annual interest rate multiplied by INTEREST_MULTIPLIER (to allow decimal numbers) * @param pAmountMax Max amount of pTokens to use as collateral * @param descriptionHash Hash of loan description * @return Index of created DebtProposal */ function createDebtProposal(uint256 debtLAmount, uint256 interest, uint256 pAmountMax, bytes32 descriptionHash) public operationAllowed(IAccessModule.Operation.CreateDebtProposal) returns(uint256) { require(debtLAmount >= limits().lDebtAmountMin(), "LoanProposalsModule: debtLAmount should be >= lDebtAmountMin"); require(interest >= limits().debtInterestMin(), "LoanProposalsModule: interest should be >= debtInterestMin"); require(openProposals[_msgSender()] < limits().maxOpenProposalsPerUser(), "LoanProposalsModule: borrower has too many open proposals"); uint256 fullCollateralLAmount = debtLAmount.mul(COLLATERAL_TO_DEBT_RATIO).div(COLLATERAL_TO_DEBT_RATIO_MULTIPLIER); uint256 clAmount = fullCollateralLAmount.mul(BORROWER_COLLATERAL_TO_FULL_COLLATERAL_RATIO).div(BORROWER_COLLATERAL_TO_FULL_COLLATERAL_MULTIPLIER); uint256 cpAmount = calculatePoolExit(clAmount); require(cpAmount <= pAmountMax, "LoanProposalsModule: pAmountMax is too low"); debtProposals[_msgSender()].push(DebtProposal({ lAmount: debtLAmount, interest: interest, descriptionHash: descriptionHash, supporters: new address[](0), lCovered: 0, pCollected: 0, created: now, executed: false })); uint256 proposalIndex = debtProposals[_msgSender()].length-1; increaseOpenProposals(_msgSender()); emit DebtProposalCreated(_msgSender(), proposalIndex, debtLAmount, interest, descriptionHash); //Add pldege of the creator DebtProposal storage prop = debtProposals[_msgSender()][proposalIndex]; prop.supporters.push(_msgSender()); prop.pledges[_msgSender()] = DebtPledge({ senderIndex: 0, lAmount: clAmount, pAmount: cpAmount }); prop.lCovered = prop.lCovered.add(clAmount); prop.pCollected = prop.pCollected.add(cpAmount); lProposals = lProposals.add(clAmount); //This is ok only while COLLATERAL_TO_DEBT_RATIO == 1 fundsModule().depositPTokens(_msgSender(), cpAmount); emit PledgeAdded(_msgSender(), _msgSender(), proposalIndex, clAmount, cpAmount); return proposalIndex; } /** * @notice Add pledge to DebtProposal * @param borrower Address of borrower * @param proposal Index of borroers's proposal * @param pAmount Amount of pTokens to use as collateral * @param lAmountMin Minimal amount of liquid tokens to cover by this pledge * * There is a case, when pAmount is too high for this debt, in this case only part of pAmount will be used. * In such edge case we may return less then lAmountMin, but price limit lAmountMin/pAmount will be honored. */ function addPledge(address borrower, uint256 proposal, uint256 pAmount, uint256 lAmountMin) public operationAllowed(IAccessModule.Operation.AddPledge) { require(_msgSender() != borrower, "LoanProposalsModule: Borrower can not add pledge"); DebtProposal storage p = debtProposals[borrower][proposal]; require(p.lAmount > 0, "LoanProposalsModule: DebtProposal not found"); require(!p.executed, "LoanProposalsModule: DebtProposal is already executed"); // p.lCovered/p.pCollected should be the same as original liquidity token to pToken exchange rate (uint256 lAmount, , ) = calculatePoolExitInverse(pAmount); require(lAmount >= lAmountMin, "LoanProposalsModule: Minimal amount is too high"); (uint256 minLPledgeAmount, uint256 maxLPledgeAmount)= getPledgeRequirements(borrower, proposal); require(maxLPledgeAmount > 0, "LoanProposalsModule: DebtProposal is already funded"); require(lAmount >= minLPledgeAmount, "LoanProposalsModule: pledge is too low"); if (lAmount > maxLPledgeAmount) { uint256 pAmountOld = pAmount; lAmount = maxLPledgeAmount; pAmount = calculatePoolExit(lAmount); assert(pAmount <= pAmountOld); // "<=" is used to handle tiny difference between lAmount and maxLPledgeAmount } if (p.pledges[_msgSender()].senderIndex == 0) { p.supporters.push(_msgSender()); p.pledges[_msgSender()] = DebtPledge({ senderIndex: p.supporters.length-1, lAmount: lAmount, pAmount: pAmount }); } else { p.pledges[_msgSender()].lAmount = p.pledges[_msgSender()].lAmount.add(lAmount); p.pledges[_msgSender()].pAmount = p.pledges[_msgSender()].pAmount.add(pAmount); } p.lCovered = p.lCovered.add(lAmount); p.pCollected = p.pCollected.add(pAmount); lProposals = lProposals.add(lAmount); //This is ok only while COLLATERAL_TO_DEBT_RATIO == 1 fundsModule().depositPTokens(_msgSender(), pAmount); emit PledgeAdded(_msgSender(), borrower, proposal, lAmount, pAmount); } /** * @notice Withdraw pledge from DebtProposal * @param borrower Address of borrower * @param proposal Index of borrowers's proposal * @param pAmount Amount of pTokens to withdraw */ function withdrawPledge(address borrower, uint256 proposal, uint256 pAmount) public operationAllowed(IAccessModule.Operation.WithdrawPledge) { require(_msgSender() != borrower, "LoanProposalsModule: Borrower can not withdraw pledge"); DebtProposal storage p = debtProposals[borrower][proposal]; require(p.lAmount > 0, "LoanProposalsModule: DebtProposal not found"); require(!p.executed, "LoanProposalsModule: DebtProposal is already executed"); DebtPledge storage pledge = p.pledges[_msgSender()]; require(pAmount <= pledge.pAmount, "LoanProposalsModule: Can not withdraw more than locked"); uint256 lAmount; if (pAmount == pledge.pAmount) { // User withdraws whole pledge lAmount = pledge.lAmount; } else { // pAmount < pledge.pAmount lAmount = pledge.lAmount.mul(pAmount).div(pledge.pAmount); assert(lAmount < pledge.lAmount); } pledge.pAmount = pledge.pAmount.sub(pAmount); pledge.lAmount = pledge.lAmount.sub(lAmount); p.pCollected = p.pCollected.sub(pAmount); p.lCovered = p.lCovered.sub(lAmount); lProposals = lProposals.sub(lAmount); //This is ok only while COLLATERAL_TO_DEBT_RATIO == 1 //Check new min/max pledge AFTER current collateral is adjusted to new values //Pledge left should either be 0 or >= minLPledgeAmount (uint256 minLPledgeAmount,)= getPledgeRequirements(borrower, proposal); require(pledge.lAmount >= minLPledgeAmount || pledge.pAmount == 0, "LoanProposalsModule: pledge left is too small"); fundsModule().withdrawPTokens(_msgSender(), pAmount); emit PledgeWithdrawn(_msgSender(), borrower, proposal, lAmount, pAmount); } function cancelDebtProposal(uint256 proposal) public operationAllowed(IAccessModule.Operation.CancelDebtProposal) { DebtProposal storage p = debtProposals[_msgSender()][proposal]; require(p.lAmount > 0, "LoanProposalsModule: DebtProposal not found"); require(now.sub(p.created) > limits().minCancelProposalTimeout(), "LoanProposalsModule: proposal can not be canceled now"); require(!p.executed, "LoanProposalsModule: DebtProposal is already executed"); for (uint256 i=0; i < p.supporters.length; i++){ address supporter = p.supporters[i]; //first supporter is borrower himself DebtPledge storage pledge = p.pledges[supporter]; lProposals = lProposals.sub(pledge.lAmount); fundsModule().withdrawPTokens(supporter, pledge.pAmount); emit PledgeWithdrawn(supporter, _msgSender(), proposal, pledge.lAmount, pledge.pAmount); delete p.pledges[supporter]; } delete p.supporters; p.lAmount = 0; //Mark proposal as deleted p.interest = 0; p.descriptionHash = 0; p.pCollected = 0; p.lCovered = 0; decreaseOpenProposals(_msgSender()); emit DebtProposalCanceled(_msgSender(), proposal); } /** * @notice Execute DebtProposal * @dev Creates Debt using data of DebtProposal * @param proposal Index of DebtProposal * @return Index of created Debt */ function executeDebtProposal(uint256 proposal) public operationAllowed(IAccessModule.Operation.ExecuteDebtProposal) returns(uint256) { address borrower = _msgSender(); DebtProposal storage p = debtProposals[borrower][proposal]; require(p.lAmount > 0, "LoanProposalsModule: DebtProposal not found"); require(getRequiredPledge(borrower, proposal) == 0, "LoanProposalsModule: DebtProposal is not fully funded"); require(!p.executed, "LoanProposalsModule: DebtProposal is already executed"); p.executed = true; lProposals = lProposals.sub(p.lCovered); //Move locked pTokens to Funds uint256[] memory amounts = new uint256[](p.supporters.length); for (uint256 i=0; i < p.supporters.length; i++) { address supporter = p.supporters[i]; amounts[i] = p.pledges[supporter].pAmount; } fundsModule().lockPTokens(p.supporters, amounts); uint256 debtIdx = loanModule().createDebt(borrower, proposal, p.lAmount); decreaseOpenProposals(borrower); emit DebtProposalExecuted(borrower, proposal, debtIdx, p.lAmount); return debtIdx; } function getProposalAndPledgeInfo(address borrower, uint256 proposal, address supporter) public view returns( uint256 lAmount, uint256 lCovered, uint256 pCollected, uint256 interest, uint256 lPledge, uint256 pPledge ){ DebtProposal storage p = debtProposals[borrower][proposal]; require(p.lAmount > 0, "LoanProposalModule: DebtProposal not found"); lAmount = p.lAmount; lCovered = p.lCovered; pCollected = p.pCollected; interest = p.interest; lPledge = p.pledges[supporter].lAmount; pPledge = p.pledges[supporter].pAmount; } function getProposalInterestRate(address borrower, uint256 proposal) public view returns(uint256){ DebtProposal storage p = debtProposals[borrower][proposal]; require(p.lAmount > 0, "LoanProposalModule: DebtProposal not found"); return p.interest; } /** * @notice Calculates how many tokens are not yet covered by borrower or supporters * @param borrower Borrower address * @param proposal Proposal index * @return amounts of liquid tokens currently required to fully cover proposal */ function getRequiredPledge(address borrower, uint256 proposal) public view returns(uint256){ DebtProposal storage p = debtProposals[borrower][proposal]; if (p.executed) return 0; uint256 fullCollateralLAmount = p.lAmount.mul(COLLATERAL_TO_DEBT_RATIO).div(COLLATERAL_TO_DEBT_RATIO_MULTIPLIER); return fullCollateralLAmount.sub(p.lCovered); } /** * @notice Calculates pledge requirements * Max allowed pledge = how many tokens are not yet covered by borrower or supporters. * @param borrower Borrower address * @param proposal Proposal index * @return minimal allowed pledge, maximal allowed pledge */ function getPledgeRequirements(address borrower, uint256 proposal) public view returns(uint256 minLPledge, uint256 maxLPledge){ // uint256 pledgePercentMin; // Minimal pledge as percent of credit amount. Value is divided to PLEDGE_PERCENT_MULTIPLIER for calculations // uint256 lMinPledgeMax; // Maximal value of minimal pledge (in liquid tokens), works together with pledgePercentMin DebtProposal storage p = debtProposals[borrower][proposal]; if (p.executed) return (0, 0); uint256 fullCollateralLAmount = p.lAmount.mul(COLLATERAL_TO_DEBT_RATIO).div(COLLATERAL_TO_DEBT_RATIO_MULTIPLIER); maxLPledge = fullCollateralLAmount.sub(p.lCovered); minLPledge = limits().pledgePercentMin().mul(fullCollateralLAmount).div(PLEDGE_PERCENT_MULTIPLIER); uint256 lMinPledgeMax = limits().lMinPledgeMax(); if (minLPledge > lMinPledgeMax) minLPledge = lMinPledgeMax; if (minLPledge > maxLPledge) minLPledge = maxLPledge; } /** * @notice Total amount of collateral locked in proposals * Although this is measured in liquid tokens, it's not actual tokens, * just a value wich is supposed to represent the collateral locked in proposals. * @return Sum of all collaterals in proposals */ function totalLProposals() public view returns(uint256){ return lProposals; } /** * @notice Calculates how many pTokens should be given to user for increasing liquidity * @param lAmount Amount of liquid tokens which will be put into the pool * @return Amount of pToken which should be sent to sender */ function calculatePoolEnter(uint256 lAmount) internal view returns(uint256) { return fundsModule().calculatePoolEnter(lAmount); } /** * @notice Calculates how many pTokens should be given to user for increasing liquidity * @param lAmount Amount of liquid tokens which will be put into the pool * @param liquidityCorrection Amount of liquid tokens to remove from liquidity because it was "virtually" withdrawn * @return Amount of pToken which should be sent to sender */ function calculatePoolEnter(uint256 lAmount, uint256 liquidityCorrection) internal view returns(uint256) { return fundsModule().calculatePoolEnter(lAmount, liquidityCorrection); } /** * @notice Calculates how many pTokens should be taken from user for decreasing liquidity * @param lAmount Amount of liquid tokens which will be removed from the pool * @return Amount of pToken which should be taken from sender */ function calculatePoolExit(uint256 lAmount) internal view returns(uint256) { return fundsModule().calculatePoolExit(lAmount); } function calculatePoolExitWithFee(uint256 lAmount) internal view returns(uint256) { return fundsModule().calculatePoolExitWithFee(lAmount); } function calculatePoolExitWithFee(uint256 lAmount, uint256 liquidityCorrection) internal view returns(uint256) { return fundsModule().calculatePoolExitWithFee(lAmount, liquidityCorrection); } /** * @notice Calculates how many liquid tokens should be removed from pool when decreasing liquidity * @param pAmount Amount of pToken which should be taken from sender * @return Amount of liquid tokens which will be removed from the pool: total, part for sender, part for pool */ function calculatePoolExitInverse(uint256 pAmount) internal view returns(uint256, uint256, uint256) { return fundsModule().calculatePoolExitInverse(pAmount); } function calculateExitFee(uint256 lAmount) internal view returns(uint256){ return ICurveModule(getModuleAddress(MODULE_CURVE)).calculateExitFee(lAmount); } function fundsModule() internal view returns(IFundsWithLoansModule) { return IFundsWithLoansModule(getModuleAddress(MODULE_FUNDS)); } function liquidityModule() internal view returns(ILiquidityModule) { return ILiquidityModule(getModuleAddress(MODULE_LIQUIDITY)); } function pToken() internal view returns(IPToken){ return IPToken(getModuleAddress(MODULE_PTOKEN)); } function loanModule() internal view returns(ILoanModule) { return ILoanModule(getModuleAddress(MODULE_LOAN)); } function limits() internal view returns(ILoanLimitsModule) { return ILoanLimitsModule(getModuleAddress(MODULE_LOAN_LIMTS)); } function increaseOpenProposals(address borrower) private { openProposals[borrower] = openProposals[borrower].add(1); } function decreaseOpenProposals(address borrower) private { openProposals[borrower] = openProposals[borrower].sub(1); } }
* @notice Withdraw pledge from DebtProposal @param borrower Address of borrower @param proposal Index of borrowers's proposal @param pAmount Amount of pTokens to withdraw/ User withdraws whole pledge pAmount < pledge.pAmount
function withdrawPledge(address borrower, uint256 proposal, uint256 pAmount) public operationAllowed(IAccessModule.Operation.WithdrawPledge) { require(_msgSender() != borrower, "LoanProposalsModule: Borrower can not withdraw pledge"); DebtProposal storage p = debtProposals[borrower][proposal]; require(p.lAmount > 0, "LoanProposalsModule: DebtProposal not found"); require(!p.executed, "LoanProposalsModule: DebtProposal is already executed"); DebtPledge storage pledge = p.pledges[_msgSender()]; require(pAmount <= pledge.pAmount, "LoanProposalsModule: Can not withdraw more than locked"); uint256 lAmount; if (pAmount == pledge.pAmount) { lAmount = pledge.lAmount; lAmount = pledge.lAmount.mul(pAmount).div(pledge.pAmount); assert(lAmount < pledge.lAmount); } pledge.pAmount = pledge.pAmount.sub(pAmount); pledge.lAmount = pledge.lAmount.sub(lAmount); p.pCollected = p.pCollected.sub(pAmount); p.lCovered = p.lCovered.sub(lAmount); require(pledge.lAmount >= minLPledgeAmount || pledge.pAmount == 0, "LoanProposalsModule: pledge left is too small"); fundsModule().withdrawPTokens(_msgSender(), pAmount); emit PledgeWithdrawn(_msgSender(), borrower, proposal, lAmount, pAmount); }
12,651,131
[ 1, 1190, 9446, 293, 19998, 628, 1505, 23602, 14592, 225, 29759, 264, 5267, 434, 29759, 264, 225, 14708, 3340, 434, 29759, 414, 1807, 14708, 225, 293, 6275, 16811, 434, 293, 5157, 358, 598, 9446, 19, 2177, 598, 9446, 87, 7339, 293, 19998, 293, 6275, 411, 293, 19998, 18, 84, 6275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 52, 19998, 12, 2867, 29759, 264, 16, 2254, 5034, 14708, 16, 2254, 5034, 293, 6275, 13, 1071, 1674, 5042, 12, 45, 1862, 3120, 18, 2988, 18, 1190, 9446, 52, 19998, 13, 288, 203, 3639, 2583, 24899, 3576, 12021, 1435, 480, 29759, 264, 16, 315, 1504, 304, 626, 22536, 3120, 30, 605, 15318, 264, 848, 486, 598, 9446, 293, 19998, 8863, 203, 3639, 1505, 23602, 14592, 2502, 293, 273, 18202, 88, 626, 22536, 63, 70, 15318, 264, 6362, 685, 8016, 15533, 203, 3639, 2583, 12, 84, 18, 80, 6275, 405, 374, 16, 315, 1504, 304, 626, 22536, 3120, 30, 1505, 23602, 14592, 486, 1392, 8863, 203, 3639, 2583, 12, 5, 84, 18, 4177, 4817, 16, 315, 1504, 304, 626, 22536, 3120, 30, 1505, 23602, 14592, 353, 1818, 7120, 8863, 203, 3639, 1505, 23602, 52, 19998, 2502, 293, 19998, 273, 293, 18, 84, 1259, 2852, 63, 67, 3576, 12021, 1435, 15533, 203, 3639, 2583, 12, 84, 6275, 1648, 293, 19998, 18, 84, 6275, 16, 315, 1504, 304, 626, 22536, 3120, 30, 4480, 486, 598, 9446, 1898, 2353, 8586, 8863, 203, 3639, 2254, 5034, 328, 6275, 31, 7010, 3639, 309, 261, 84, 6275, 422, 293, 19998, 18, 84, 6275, 13, 288, 203, 5411, 328, 6275, 273, 293, 19998, 18, 80, 6275, 31, 203, 5411, 328, 6275, 273, 293, 19998, 18, 80, 6275, 18, 16411, 12, 84, 6275, 2934, 2892, 12, 84, 19998, 18, 84, 6275, 1769, 203, 5411, 1815, 12, 80, 6275, 411, 293, 19998, 18, 80, 6275, 1769, 203, 3639, 289, 203, 2 ]
/** * @title ERC20 interface * @dev Implements ERC20 Token Standard: https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function transfer(address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function balanceOf(address _owner) public view returns (uint256 balance); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function sub(uint256 x, uint256 y) internal pure returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function mul(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x * y; assert((x == 0) || (z / x == y)); return z; } function div(uint256 x, uint256 y) internal pure returns(uint256) { assert(y != 0); uint256 z = x / y; assert(x == y * z + x % y); return z; } } /// @title Contract that will work with ERC223 tokens. contract ERC223ReceivingContract { /* * @dev Standard ERC223 function that will handle incoming token transfers. * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) external; } /** * @title Ownable contract * @dev The Ownable contract has an owner address, and provides basic authorization control functions. */ contract Ownable { address public owner; // Modifiers modifier onlyOwner() { require(msg.sender == owner); _; } modifier validAddress(address _address) { require(_address != address(0)); _; } // Events event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); /// @dev The Ownable constructor sets the original `owner` of the contract to the sender account. constructor(address _owner) public validAddress(_owner) { owner = _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 validAddress(_newOwner) { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC223 is ERC20 { function transfer(address _to, uint256 _value, bytes _data) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } contract StandardToken is ERC223 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; // Modifiers modifier validAddress(address _address) { require(_address != address(0)); _; } /* * @dev ERC20 method to transfer token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { bytes memory empty; transfer(_to, _value, empty); } /* * @dev ERC223 method to transfer token to a specified address with data. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint256 _value, bytes _data) public validAddress(_to) returns (bool success) { uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); // Call token fallback function if _to is a contract. Rejects if not implemented. if (codeLength > 0) { ERC223ReceivingContract(_to).tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value, _data); return true; } /* * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* * @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 validAddress(_to) returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _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]; } /* * @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]; } } contract MintableToken is StandardToken, Ownable { // Events event Mint(uint256 supply, address indexed to, uint256 amount); function tokenTotalSupply() public pure returns (uint256); /// @dev Allows the owner to mint new tokens /// @param _to Address to mint the tokens to /// @param _amount Amount of tokens that will be minted /// @return Boolean to signify successful minting function mint(address _to, uint256 _amount) external onlyOwner returns (bool) { require(totalSupply.add(_amount) <= tokenTotalSupply()); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(totalSupply, _to, _amount); emit Transfer(address(0), _to, _amount); return true; } } contract BodhiEthereum is MintableToken { // Token configurations string public constant name = "Bodhi Ethereum"; string public constant symbol = "BOE"; uint256 public constant decimals = 8; constructor() Ownable(msg.sender) public { } // 100 million BOE ever created function tokenTotalSupply() public pure returns (uint256) { return 100 * (10**6) * (10**decimals); } }
* @title ERC20 interface/
contract ERC20 { uint256 public totalSupply; function transfer(address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function balanceOf(address _owner) public view returns (uint256 balance); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
4,811,062
[ 1, 654, 39, 3462, 1560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 288, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 11890, 5034, 11013, 1769, 203, 565, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 4463, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.7; interface ILayerZeroUserApplicationConfig { // @notice set the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _configType - type of configuration. every messaging library has its own convention. // @param _config - configuration in the bytes. can encode arbitrary content. function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external; // @notice set the send() LayerZero messaging library version to _version // @param _version - new messaging library version function setSendVersion(uint16 _version) external; // @notice set the lzReceive() LayerZero messaging library version to _version // @param _version - new messaging library version function setReceiveVersion(uint16 _version) external; // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload // @param _srcChainId - the chainId of the source chain // @param _srcAddress - the contract address of the source contract at the source chain function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; } interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig { // @notice send a LayerZero message to the specified address at a LayerZero endpoint. // @param _dstChainId - the destination chain identifier // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains // @param _payload - a custom bytes payload to send to the destination contract // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable; // @notice used by the messaging library to publish verified payload // @param _srcChainId - the source chain identifier // @param _srcAddress - the source contract (as bytes) at the source chain // @param _dstAddress - the address on destination chain // @param _nonce - the unbound message ordering nonce // @param _gasLimit - the gas limit for external contract execution // @param _payload - verified payload to send to the destination contract function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external; // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64); // @notice get the outboundNonce from this source chain which, consequently, is always an EVM // @param _srcAddress - the source chain contract address function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64); // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery // @param _dstChainId - the destination chain identifier // @param _userApplication - the user app address on this EVM chain // @param _payload - the custom message to send over LayerZero // @param _payInZRO - if false, user app pays the protocol fee in native token // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee); // @notice get this Endpoint's immutable source identifier function getChainId() external view returns (uint16); // @notice the interface to retry failed message on this Endpoint destination // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address // @param _payload - the payload to be retried function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external; // @notice query if any STORED payload (message blocking) at the endpoint. // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool); // @notice query if the _libraryAddress is valid for sending msgs. // @param _userApplication - the user app address on this EVM chain function getSendLibraryAddress(address _userApplication) external view returns (address); // @notice query if the _libraryAddress is valid for receiving msgs. // @param _userApplication - the user app address on this EVM chain function getReceiveLibraryAddress(address _userApplication) external view returns (address); // @notice query if the non-reentrancy guard for send() is on // @return true if the guard is on. false otherwise function isSendingPayload() external view returns (bool); // @notice query if the non-reentrancy guard for receive() is on // @return true if the guard is on. false otherwise function isReceivingPayload() external view returns (bool); // @notice get the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _userApplication - the contract address of the user application // @param _configType - type of configuration. every messaging library has its own convention. function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory); // @notice get the send() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getSendVersion(address _userApplication) external view returns (uint16); // @notice get the lzReceive() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getReceiveVersion(address _userApplication) external view returns (uint16); } interface ILayerZeroReceiver { // @notice LayerZero endpoint will invoke this function to deliver the message on the destination // @param _srcChainId - the source endpoint identifier // @param _srcAddress - the source sending contract address from the source chain // @param _nonce - the ordered message nonce // @param _payload - the signed payload is the UA bytes has encoded to be sent function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external; } // 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 (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 (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 (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 (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/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 (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/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 (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/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"); _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 {} } abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver { ILayerZeroEndpoint internal endpoint; struct FailedMessages { uint payloadLength; bytes32 payloadHash; } mapping(uint16 => mapping(bytes => mapping(uint => FailedMessages))) public failedMessages; mapping(uint16 => bytes) public trustedRemoteLookup; event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload); function lzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) external override { require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security require(_srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]), "NonblockingReceiver: invalid source sending contract"); // try-catch all errors/exceptions // having failed messages does not block messages passing try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) { // do nothing } catch { // error / exception failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(_payload.length, keccak256(_payload)); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload); } } function onLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public { // only internal transaction require(msg.sender == address(this), "NonblockingReceiver: caller must be Bridge."); // handle incoming message _LzReceive( _srcChainId, _srcAddress, _nonce, _payload); } // abstract function function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) virtual internal; function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam) internal { endpoint.send{value: msg.value}(_dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam); } function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable { // assert there is message to retry FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce]; require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message"); require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload"); // clear the stored message failedMsg.payloadLength = 0; failedMsg.payloadHash = bytes32(0); // execute the message. revert if it fails again this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner { trustedRemoteLookup[_chainId] = _trustedRemote; } } contract TheMeld is Ownable, ERC721, NonblockingReceiver { address public _owner; string private baseURI; string private _contractURI; uint256 nextTokenId = 1; uint256 MAX_MINT_ETHEREUM = 250; uint gasForDestinationLzReceive = 350000; constructor() ERC721("TheMeld", "mld") { _owner = msg.sender; } function contractURI() public view returns (string memory) { return _contractURI; } function setContractURI(string memory URI) external onlyOwner { _contractURI = URI; } function setILayerZeroEndpoint(address _layerZeroEndpoint) external onlyOwner { endpoint = ILayerZeroEndpoint(_layerZeroEndpoint); } // mint function // you can choose to mint 1 or 2 // mint is free, but payments are accepted function mint(uint8 numTokens) external payable { require(numTokens < 3, "Max 2 NFTs per transaction"); require(nextTokenId + numTokens <= MAX_MINT_ETHEREUM, "Mint exceeds supply"); _safeMint(msg.sender, ++nextTokenId); if (numTokens == 2) { _safeMint(msg.sender, ++nextTokenId); } } // This function transfers the nft from your address on the // source chain to the same address on the destination chain function traverseChains(uint16 _chainId, uint tokenId) public payable { require(msg.sender == ownerOf(tokenId), "You must own the token to traverse"); require(trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel"); // abi.encode() the payload with the values to send bytes memory payload = abi.encode(msg.sender, tokenId); // encode adapterParams to specify more gas for the destination uint16 version = 1; bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive); // get the fees we need to pay to LayerZero + Relayer to cover message delivery // you will be refunded for extra gas paid (uint messageFee, ) = endpoint.estimateFees(_chainId, address(this), payload, false, adapterParams); require(msg.value >= messageFee, string(abi.encodePacked("You have to send some/more ETH to cover traversal gas fee estimate. You will be refunded the difference. Estimate: ", Strings.toString(messageFee)))); endpoint.send{value: msg.value}( _chainId, // destination chainId trustedRemoteLookup[_chainId], // destination address of nft contract payload, // abi.encoded()'ed bytes payable(msg.sender), // refund address address(0x0), // 'zroPaymentAddress' unused for this adapterParams // txParameters ); // burn NFT, eliminating it from circulation on src chain _burn(tokenId); } function setBaseURI(string memory URI) external onlyOwner { baseURI = URI; } function donate() external payable { // thank you } // This allows the devs to receive kind donations function withdraw(uint amt) external onlyOwner { (bool sent, ) = payable(_owner).call{value: amt}(""); require(sent, "Failed to withdraw Ether"); } // just in case this fixed variable limits us from future integrations function setGasForDestinationLzReceive(uint newVal) external onlyOwner { gasForDestinationLzReceive = newVal; } // ------------------ // Internal Functions // ------------------ function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) override internal { // decode (address toAddr, uint tokenId) = abi.decode(_payload, (address, uint)); // mint the tokens back into existence on destination chain _safeMint(toAddr, tokenId); } function _baseURI() override internal view returns (string memory) { return baseURI; } }
mint function you can choose to mint 1 or 2 mint is free, but payments are accepted
function mint(uint8 numTokens) external payable { require(numTokens < 3, "Max 2 NFTs per transaction"); require(nextTokenId + numTokens <= MAX_MINT_ETHEREUM, "Mint exceeds supply"); _safeMint(msg.sender, ++nextTokenId); if (numTokens == 2) { _safeMint(msg.sender, ++nextTokenId); } }
1,450,280
[ 1, 81, 474, 445, 1846, 848, 9876, 358, 312, 474, 404, 578, 576, 312, 474, 353, 4843, 16, 1496, 25754, 854, 8494, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 11890, 28, 818, 5157, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 2107, 5157, 411, 890, 16, 315, 2747, 576, 423, 4464, 87, 1534, 2492, 8863, 203, 3639, 2583, 12, 4285, 1345, 548, 397, 818, 5157, 1648, 4552, 67, 49, 3217, 67, 1584, 4298, 2799, 16, 315, 49, 474, 14399, 14467, 8863, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 965, 4285, 1345, 548, 1769, 203, 3639, 309, 261, 2107, 5157, 422, 576, 13, 288, 203, 5411, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 965, 4285, 1345, 548, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xbD852Af274e5534B5c7e134b3535745680529fb6/sources/browser/ONXFarming.sol
Update dev address by the previous dev or governance
function changeDevAddr(address _devAddr) public { require(msg.sender == devAddr, 'bruh'); devAddr = _devAddr; }
2,898,174
[ 1, 1891, 4461, 1758, 635, 326, 2416, 4461, 578, 314, 1643, 82, 1359, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 8870, 3178, 12, 2867, 389, 5206, 3178, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4461, 3178, 16, 296, 2848, 89, 76, 8284, 203, 3639, 4461, 3178, 273, 389, 5206, 3178, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /* _ __ __ ____ _ ____ _ _ _ / \ | \/ | _ \| | / ___| ___ | | __| | (_) ___ / _ \ | |\/| | |_) | | | | _ / _ \| |/ _` | | |/ _ \ / ___ \| | | | __/| |__| |_| | (_) | | (_| | _ | | (_) | /_/ \_\_| |_|_| |_____\____|\___/|_|\__,_| (_) |_|\___/ Ample Gold $AMPLG is a goldpegged defi protocol that is based on Ampleforths elastic tokensupply model. AMPLG is designed to maintain its base price target of 0.01g of Gold with a progammed inflation adjustment (rebase). Forked from Ampleforth: https://github.com/ampleforth/uFragments (Credits to Ampleforth team for implementation of rebasing on the ethereum network) GPL 3.0 license AMPLG_GoldPolicy.sol - AMPLG Gold Orchestrator Policy */ pragma solidity ^0.6.12; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface IAMPLG { function totalSupply() external view returns (uint256); function rebaseGold(uint256 epoch, int256 supplyDelta) external returns (uint256); } interface IOracle { function getData() external view returns (uint256, bool); } interface IGoldOracle { function getGoldPrice() external view returns (uint256, bool); function getMarketPrice() external view returns (uint256, bool); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { _owner = msg.sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title AMPLG $AMPLG Gold Supply Policy * @dev This is the extended orchestrator version of the AMPLG $AMPLG Ideal Gold Pegged DeFi protocol aka Ampleforth Gold ($AMPLG). * AMPLG operates symmetrically on expansion and contraction. It will both split and * combine coins to maintain a stable gold unit price against PAX gold. * * This component regulates the token supply of the AMPLG ERC20 token in response to * market oracles and gold price. */ contract AMPLGGoldPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 goldPrice, int256 requestedSupplyAdjustment, uint256 timestampSec ); IAMPLG public amplg; // Gold oracle provides the gold price and market price. IGoldOracle public goldOracle; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; constructor() public { deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 6; minRebaseTimeIntervalSec = 12 hours; lastRebaseTimestampSec = 0; epoch = 0; } /** * @notice Returns true if at least minRebaseTimeIntervalSec seconds have passed since last rebase. * */ function canRebase() public view returns (bool) { return (lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * */ function rebase() external { require(canRebase(), "AMPLG Error: Insufficient time has passed since last rebase."); require(tx.origin == msg.sender); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 curGoldPrice, uint256 marketPrice, int256 targetRate, int256 supplyDelta) = getRebaseValues(); uint256 supplyAfterRebase = amplg.rebaseGold(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, marketPrice, curGoldPrice, supplyDelta, now); } /** * @notice Calculates the supplyDelta and returns the current set of values for the rebase * * @dev The supply adjustment equals the formula * (current price – base target price in usd) * total supply / (base target price in usd * lag * factor) */ function getRebaseValues() public view returns (uint256, uint256, int256, int256) { uint256 curGoldPrice; bool goldValid; (curGoldPrice, goldValid) = goldOracle.getGoldPrice(); require(goldValid); uint256 marketPrice; bool marketValid; (marketPrice, marketValid) = goldOracle.getMarketPrice(); require(marketValid); int256 goldPriceSigned = curGoldPrice.toInt256Safe(); int256 marketPriceSigned = marketPrice.toInt256Safe(); int256 rate = marketPriceSigned.sub(goldPriceSigned); if (marketPrice > MAX_RATE) { marketPrice = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(marketPrice, curGoldPrice); if (supplyDelta > 0 && amplg.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(amplg.totalSupply())).toInt256Safe(); } return (curGoldPrice, marketPrice, rate, supplyDelta); } /** * @return Computes the total supply adjustment in response to the market price * and the current gold price. */ function computeSupplyDelta(uint256 marketPrice, uint256 curGoldPrice) internal view returns (int256) { if (withinDeviationThreshold(marketPrice, curGoldPrice)) { return 0; } //(current price – base target price in usd) * total supply / (base target price in usd * lag factor) int256 goldPrice = curGoldPrice.toInt256Safe(); int256 marketPrice = marketPrice.toInt256Safe(); int256 delta = marketPrice.sub(goldPrice); int256 lagSpawn = marketPrice.mul(rebaseLag.toInt256Safe()); return amplg.totalSupply().toInt256Safe() .mul(delta).div(lagSpawn); } /** * @notice Sets the rebase lag parameter. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameter which control the timing and frequency of * rebase operations the minimum time period that must elapse between rebase cycles. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. */ function setRebaseTimingParameter(uint256 minRebaseTimeIntervalSec_) external onlyOwner { minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; } /** * @param rate The current market price * @param targetRate The current gold price * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /** * @notice Sets the reference to the AMPLG token governed. * Can only be called once during initialization. * * @param amplg_ The address of the AMPLG ERC20 token. */ function setAMPLG(IAMPLG amplg_) external onlyOwner { require(amplg == IAMPLG(0)); amplg = amplg_; } /** * @notice Sets the reference to the AMPLG $AMPLG oracle. * @param _goldOracle The address of the AMPLG oracle contract. */ function setGoldOracle(IGoldOracle _goldOracle) external onlyOwner { goldOracle = _goldOracle; } }
* @title AMPLG $AMPLG Gold Supply Policy @dev This is the extended orchestrator version of the AMPLG $AMPLG Ideal Gold Pegged DeFi protocol aka Ampleforth Gold ($AMPLG). AMPLG operates symmetrically on expansion and contraction. It will both split and combine coins to maintain a stable gold unit price against PAX gold. This component regulates the token supply of the AMPLG ERC20 token in response to market oracles and gold price./ Gold oracle provides the gold price and market price. If the current exchange rate is within this fractional distance from the target, no supply update is performed. Fixed point number--same format as the rate. (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. DECIMALS Fixed point number. The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag Check setRebaseLag comments for more details. Natural number, no decimal places. More than this much time must pass between rebase operations. Block timestamp of last rebase operation The number of rebase cycles since inception Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. Both are 18 decimals fixed point numbers. MAX_SUPPLY = MAX_INT256 / MAX_RATE
contract AMPLGGoldPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 goldPrice, int256 requestedSupplyAdjustment, uint256 timestampSec ); IAMPLG public amplg; IGoldOracle public goldOracle; uint256 public deviationThreshold; uint256 public rebaseLag; uint256 public minRebaseTimeIntervalSec; uint256 public lastRebaseTimestampSec; uint256 public epoch; uint256 private constant DECIMALS = 18; uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; constructor() public { deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 6; minRebaseTimeIntervalSec = 12 hours; lastRebaseTimestampSec = 0; epoch = 0; } function canRebase() public view returns (bool) { return (lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); } function rebase() external { require(canRebase(), "AMPLG Error: Insufficient time has passed since last rebase."); require(tx.origin == msg.sender); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 curGoldPrice, uint256 marketPrice, int256 targetRate, int256 supplyDelta) = getRebaseValues(); uint256 supplyAfterRebase = amplg.rebaseGold(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, marketPrice, curGoldPrice, supplyDelta, now); } function getRebaseValues() public view returns (uint256, uint256, int256, int256) { uint256 curGoldPrice; bool goldValid; (curGoldPrice, goldValid) = goldOracle.getGoldPrice(); require(goldValid); uint256 marketPrice; bool marketValid; (marketPrice, marketValid) = goldOracle.getMarketPrice(); require(marketValid); int256 goldPriceSigned = curGoldPrice.toInt256Safe(); int256 marketPriceSigned = marketPrice.toInt256Safe(); int256 rate = marketPriceSigned.sub(goldPriceSigned); if (marketPrice > MAX_RATE) { marketPrice = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(marketPrice, curGoldPrice); if (supplyDelta > 0 && amplg.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(amplg.totalSupply())).toInt256Safe(); } return (curGoldPrice, marketPrice, rate, supplyDelta); } function getRebaseValues() public view returns (uint256, uint256, int256, int256) { uint256 curGoldPrice; bool goldValid; (curGoldPrice, goldValid) = goldOracle.getGoldPrice(); require(goldValid); uint256 marketPrice; bool marketValid; (marketPrice, marketValid) = goldOracle.getMarketPrice(); require(marketValid); int256 goldPriceSigned = curGoldPrice.toInt256Safe(); int256 marketPriceSigned = marketPrice.toInt256Safe(); int256 rate = marketPriceSigned.sub(goldPriceSigned); if (marketPrice > MAX_RATE) { marketPrice = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(marketPrice, curGoldPrice); if (supplyDelta > 0 && amplg.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(amplg.totalSupply())).toInt256Safe(); } return (curGoldPrice, marketPrice, rate, supplyDelta); } function getRebaseValues() public view returns (uint256, uint256, int256, int256) { uint256 curGoldPrice; bool goldValid; (curGoldPrice, goldValid) = goldOracle.getGoldPrice(); require(goldValid); uint256 marketPrice; bool marketValid; (marketPrice, marketValid) = goldOracle.getMarketPrice(); require(marketValid); int256 goldPriceSigned = curGoldPrice.toInt256Safe(); int256 marketPriceSigned = marketPrice.toInt256Safe(); int256 rate = marketPriceSigned.sub(goldPriceSigned); if (marketPrice > MAX_RATE) { marketPrice = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(marketPrice, curGoldPrice); if (supplyDelta > 0 && amplg.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(amplg.totalSupply())).toInt256Safe(); } return (curGoldPrice, marketPrice, rate, supplyDelta); } function computeSupplyDelta(uint256 marketPrice, uint256 curGoldPrice) internal view returns (int256) { if (withinDeviationThreshold(marketPrice, curGoldPrice)) { return 0; } int256 marketPrice = marketPrice.toInt256Safe(); int256 delta = marketPrice.sub(goldPrice); int256 lagSpawn = marketPrice.mul(rebaseLag.toInt256Safe()); return amplg.totalSupply().toInt256Safe() .mul(delta).div(lagSpawn); } function computeSupplyDelta(uint256 marketPrice, uint256 curGoldPrice) internal view returns (int256) { if (withinDeviationThreshold(marketPrice, curGoldPrice)) { return 0; } int256 marketPrice = marketPrice.toInt256Safe(); int256 delta = marketPrice.sub(goldPrice); int256 lagSpawn = marketPrice.mul(rebaseLag.toInt256Safe()); return amplg.totalSupply().toInt256Safe() .mul(delta).div(lagSpawn); } int256 goldPrice = curGoldPrice.toInt256Safe(); function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } function setRebaseTimingParameter(uint256 minRebaseTimeIntervalSec_) external onlyOwner { minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; } function withinDeviationThreshold(uint256 rate, uint256 targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } function setAMPLG(IAMPLG amplg_) external onlyOwner { require(amplg == IAMPLG(0)); amplg = amplg_; } function setGoldOracle(IGoldOracle _goldOracle) external onlyOwner { goldOracle = _goldOracle; } }
1,575,236
[ 1, 2192, 6253, 43, 271, 2192, 6253, 43, 611, 1673, 3425, 1283, 7436, 225, 1220, 353, 326, 7021, 578, 23386, 639, 1177, 434, 326, 432, 4566, 48, 43, 271, 2192, 6253, 43, 23062, 287, 611, 1673, 453, 1332, 2423, 1505, 42, 77, 1771, 28105, 432, 1291, 298, 1884, 451, 611, 1673, 9253, 2192, 6253, 43, 2934, 1377, 432, 4566, 48, 43, 2255, 815, 15108, 1230, 603, 17965, 471, 16252, 1128, 18, 2597, 903, 3937, 1416, 471, 1377, 8661, 276, 9896, 358, 17505, 279, 14114, 20465, 2836, 6205, 5314, 453, 2501, 20465, 18, 1377, 1220, 1794, 960, 17099, 326, 1147, 14467, 434, 326, 432, 4566, 48, 43, 4232, 39, 3462, 1147, 316, 766, 358, 1377, 13667, 578, 69, 9558, 471, 20465, 6205, 18, 19, 611, 1673, 20865, 8121, 326, 20465, 6205, 471, 13667, 6205, 18, 971, 326, 783, 7829, 4993, 353, 3470, 333, 20462, 3888, 628, 326, 1018, 16, 1158, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 432, 4566, 48, 19491, 1673, 2582, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 1702, 364, 509, 5034, 31, 203, 565, 1450, 29810, 5034, 5664, 364, 2254, 5034, 31, 203, 203, 565, 871, 1827, 426, 1969, 12, 203, 3639, 2254, 5034, 8808, 7632, 16, 203, 3639, 2254, 5034, 7829, 4727, 16, 203, 3639, 2254, 5034, 20465, 5147, 16, 203, 3639, 509, 5034, 3764, 3088, 1283, 19985, 16, 203, 3639, 2254, 5034, 2858, 2194, 203, 565, 11272, 203, 203, 565, 9983, 6253, 43, 1071, 2125, 412, 75, 31, 203, 203, 565, 13102, 1673, 23601, 1071, 20465, 23601, 31, 203, 203, 565, 2254, 5034, 1071, 17585, 7614, 31, 203, 203, 565, 2254, 5034, 1071, 283, 1969, 26093, 31, 203, 203, 565, 2254, 5034, 1071, 1131, 426, 1969, 950, 4006, 2194, 31, 203, 203, 565, 2254, 5034, 1071, 1142, 426, 1969, 4921, 2194, 31, 203, 203, 565, 2254, 5034, 1071, 7632, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 25429, 55, 273, 6549, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 24062, 273, 1728, 636, 26, 380, 1728, 636, 23816, 55, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 13272, 23893, 273, 4871, 12, 11890, 5034, 12, 21, 13, 2296, 4561, 13, 342, 4552, 67, 24062, 31, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 17585, 7614, 273, 1381, 380, 1728, 2826, 261, 23816, 55, 17, 22, 1769, 203, 203, 3639, 283, 1969, 26093, 273, 1666, 31, 203, 3639, 1131, 426, 1969, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; interface ILegitArtERC721 { function mintTo( address creator, uint256 royaltyFee, address gallerist, uint256 galleristFee, address to, uint256 tokenId, string memory tokenURI ) external; function getFeeInfo(uint256 tokenId) external view returns ( address creator, uint256 royaltyFee, address gallerist, uint256 galleristFee ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../MarketPlaceCore.sol"; import "../interfaces/ILegitArtERC721.sol"; contract MarketPlaceCoreMock is MarketPlaceCore { constructor( IERC20 _usdc, ILegitArtERC721 _legitArtNFT, address _feeBeneficiary, uint256 _primaryFeePercentage, uint256 _secondaryFeePercentage ) MarketPlaceCore(_usdc, _legitArtNFT, _feeBeneficiary, _primaryFeePercentage, _secondaryFeePercentage) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/ILegitArtERC721.sol"; import "./registry/AuthenticatedProxy.sol"; /// @title LegitArt Marketplace abstract contract MarketPlaceCore is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; enum OrderStatus { PLACED, CANCELED, EXECUTED } struct Order { address nftContract; uint256 tokenId; address seller; address buyer; uint256 price; uint256 createdAt; OrderStatus status; } mapping(bytes32 => Order) public orders; IERC20 public immutable usdc; ILegitArtERC721 public legitArtNFT; address public feeBeneficiary; uint256 public primaryFeePercentage; // Use 1e18 for 100% uint256 public secondaryFeePercentage; // Use 1e18 for 100% event OrderPlaced( bytes32 indexed orderId, address indexed nftContract, uint256 indexed tokenId, address seller, uint256 price ); event OrderExecuted( bytes32 indexed orderId, address buyer, uint256 feeToProtocol, uint256 feeToCreator, uint256 feeToGallerist ); event OrderCanceled(bytes32 indexed orderId); event OrderUpdated(bytes32 indexed orderId, uint256 newPrice); event FeeBeneficiaryUpdated(address indexed oldFeeBeneficiary, address indexed newFeeBeneficiary); event PrimaryFeePercentageUpdated(uint256 oldPrimaryFeePercentage, uint256 newPrimaryFeePercentage); event SecondaryFeePercentageUpdated(uint256 oldSecondaryFeePercentage, uint256 newSecondaryFeePercentage); constructor( IERC20 _usdc, ILegitArtERC721 _legitArtNFT, address _feeBeneficiary, uint256 _primaryFeePercentage, uint256 _secondaryFeePercentage ) { usdc = _usdc; legitArtNFT = _legitArtNFT; feeBeneficiary = _feeBeneficiary; primaryFeePercentage = _primaryFeePercentage; secondaryFeePercentage = _secondaryFeePercentage; } /// @notice Store a new order function _storeOrder( address _nftContract, uint256 _tokenId, uint256 _price, uint256 _createdAt, address _seller, address _buyer, OrderStatus _status ) internal returns (bytes32 orderId) { orderId = _getOrderIdFromFields(_nftContract, _tokenId, _price, _createdAt, _seller); require(!_orderExists(orderId), "Order stored already"); Order memory order = Order({ nftContract: _nftContract, tokenId: _tokenId, seller: _seller, buyer: _buyer, price: _price, createdAt: _createdAt, status: _status }); orders[orderId] = order; } function _bytesToAddress(bytes memory _bytes) private pure returns (address _address) { assembly { _address := mload(add(_bytes, 32)) } } /// @notice Place an item for sale on the marketplace function _placeOrder( address _nftContract, uint256 _tokenId, uint256 _price, address _seller ) internal returns (bytes32 orderId) { require(_nftContract != address(0), "NFT contract can not be null"); orderId = _storeOrder( _nftContract, _tokenId, _price, block.timestamp, _seller, address(0), // buyer OrderStatus.PLACED ); // Transfer user's NFT by calling his proxy bytes memory call = abi.encodeWithSignature( "transferFrom(address,address,uint256)", _seller, address(this), _tokenId ); _getProxyFromMsgSender().proxy(_nftContract, AuthenticatedProxy.HowToCall.Call, call); emit OrderPlaced(orderId, _nftContract, _tokenId, _seller, _price); } function _getProxyFromMsgSender() internal view returns (AuthenticatedProxy) { require(Address.isContract(_msgSender()), "The caller is not a proxy"); return AuthenticatedProxy(_msgSender()); } function _getUserFromMsgSender() internal view returns (address) { return _getProxyFromMsgSender().user(); } /// @notice Place an item for sale on the marketplace function placeOrder( address _nftContract, uint256 _tokenId, uint256 _price ) external nonReentrant returns (bytes32 orderId) { address seller = _getUserFromMsgSender(); orderId = _placeOrder(_nftContract, _tokenId, _price, seller); } /// @notice Check if an order exists function _orderExists(bytes32 _orderId) internal view returns (bool) { return orders[_orderId].nftContract != address(0); } /// @notice Payment processor for secondary market function _processOrderPayment(Order memory order, address _payer) internal virtual returns ( uint256 _toProtocol, uint256 _toCreator, uint256 _toGallerist, uint256 _toSeller ) { _toProtocol = (order.price * secondaryFeePercentage) / 1e18; if (_toProtocol > 0) { usdc.safeTransferFrom(_payer, feeBeneficiary, _toProtocol); } (address _creator, uint256 _royaltyFee, address _gallerist, uint256 _galleristFee) = legitArtNFT.getFeeInfo( order.tokenId ); uint256 _royalty = (order.price * _royaltyFee) / 1e18; if (_royalty > 0) { _toGallerist = (_royalty * _galleristFee) / 1e18; if (_toGallerist > 0) { usdc.safeTransferFrom(_payer, _gallerist, _toGallerist); } _toCreator = _royalty - _toGallerist; usdc.safeTransferFrom(_payer, _creator, _toCreator); } _toSeller = order.price - _toProtocol - _royalty; usdc.safeTransferFrom(_payer, order.seller, _toSeller); } /// @notice Execute a placed order function _executeOrder( bytes32 _orderId, address _buyer, address _payer ) private { require(_orderExists(_orderId), "Order does not exist"); Order storage order = orders[_orderId]; require(order.status == OrderStatus.PLACED, "Order status is not valid"); order.buyer = _buyer; order.status = OrderStatus.EXECUTED; (uint256 _toProtocol, uint256 _toCreator, uint256 _toGallerist, ) = _processOrderPayment(order, _payer); IERC721(order.nftContract).transferFrom(address(this), _buyer, order.tokenId); emit OrderExecuted(_orderId, _buyer, _toProtocol, _toCreator, _toGallerist); } /// @notice Execute a placed order function executeOrderOnBehalf(bytes32 _orderId, address _buyer) external nonReentrant { address _payer = _msgSender(); _executeOrder(_orderId, _buyer, _payer); } /// @notice Execute a placed order function executeOrder(bytes32 _orderId) external nonReentrant { address _buyerAndPayer = _getUserFromMsgSender(); _executeOrder(_orderId, _buyerAndPayer, _buyerAndPayer); } /// @notice Cancel a placed order function cancelOrder(bytes32 _orderId) external nonReentrant { require(_orderExists(_orderId), "Order does not exist"); Order storage order = orders[_orderId]; require(_getUserFromMsgSender() == order.seller, "Only seller can cancel an order"); require(order.status == OrderStatus.PLACED, "Order status is not valid"); order.status = OrderStatus.CANCELED; IERC721(order.nftContract).transferFrom(address(this), order.seller, order.tokenId); emit OrderCanceled(_orderId); } function updateOrder(bytes32 _orderId, uint256 _newPrice) external nonReentrant { require(_orderExists(_orderId), "Order does not exist"); Order storage order = orders[_orderId]; require(_getUserFromMsgSender() == order.seller, "Only seller can update an order"); require(order.status == OrderStatus.PLACED, "Order status is not valid"); order.price = _newPrice; emit OrderUpdated(_orderId, _newPrice); } /// @notice Generate orderId for a given order by hashing the key params function _getOrderIdFromFields( address _nftContract, uint256 _tokenId, uint256 _price, uint256 _createdAt, address _seller ) internal pure returns (bytes32 orderId) { orderId = keccak256(abi.encode(_nftContract, _tokenId, _price, _createdAt, _seller)); } function updateFeeBeneficiary(address _newFeeBenenficiary) public onlyOwner { require(_newFeeBenenficiary != address(0), "Beneficiary is invalid"); require(_newFeeBenenficiary != feeBeneficiary, "Beneficiary is the same as current"); emit FeeBeneficiaryUpdated(feeBeneficiary, _newFeeBenenficiary); feeBeneficiary = _newFeeBenenficiary; } function updatePrimaryFeePercentage(uint256 _newPrimaryFeePercentage) public onlyOwner { require(_newPrimaryFeePercentage <= 1e18, "Fee is greater than 100%"); require(_newPrimaryFeePercentage != primaryFeePercentage, "Fee is the same as current"); emit PrimaryFeePercentageUpdated(primaryFeePercentage, _newPrimaryFeePercentage); primaryFeePercentage = _newPrimaryFeePercentage; } function updateSecondaryFeePercentage(uint256 _newSecondaryFeePercentage) public onlyOwner { require(_newSecondaryFeePercentage <= 1e18, "Fee is greater than 100%"); require(_newSecondaryFeePercentage != secondaryFeePercentage, "Fee is the same as current"); emit SecondaryFeePercentageUpdated(secondaryFeePercentage, _newSecondaryFeePercentage); secondaryFeePercentage = _newSecondaryFeePercentage; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT /* Proxy contract to hold access to assets on behalf of a user (e.g. ERC20 approve) and execute calls under particular conditions. */ pragma solidity 0.8.4; import "./ProxyRegistry.sol"; import "./TokenRecipient.sol"; import "./proxy/OwnedUpgradeableProxyStorage.sol"; /** * @title AuthenticatedProxy * @author Wyvern Protocol Developers */ contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeableProxyStorage { /* Whether initialized. */ bool initialized = false; /* Address which owns this proxy. */ address public user; /* Associated registry with contract authentication information. */ ProxyRegistry public registry; /* Whether access has been revoked. */ bool public revoked; /* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */ enum HowToCall { Call, DelegateCall } /* Event fired when the proxy access is revoked or unrevoked. */ event Revoked(bool revoked); /** * Initialize an AuthenticatedProxy * * @param addrUser Address of user on whose behalf this proxy will act * @param addrRegistry Address of ProxyRegistry contract which will manage this proxy */ function initialize(address addrUser, ProxyRegistry addrRegistry) public { require(!initialized, "Authenticated proxy already initialized"); initialized = true; user = addrUser; registry = addrRegistry; } /** * Set the revoked flag (allows a user to revoke ProxyRegistry access) * * @dev Can be called by the user only * @param revoke Whether or not to revoke access */ function setRevoke(bool revoke) public { require(msg.sender == user, "Authenticated proxy can only be revoked by its user"); revoked = revoke; emit Revoked(revoke); } function multi( address[] memory dest, HowToCall[] memory howToCall, bytes[] memory data ) public returns (bool[] memory result) { require( dest.length == howToCall.length && howToCall.length == data.length, "arrays length have not the same length" ); result = new bool[](dest.length); for (uint256 i = 0; i < dest.length; ++i) { result[i] = proxy(dest[i], howToCall[i], data[i]); } } /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param data Calldata to send * @return result Result of the call (success or failure) */ function proxy( address dest, HowToCall howToCall, bytes memory data ) public returns (bool result) { require( msg.sender == user || (!revoked && registry.contracts(msg.sender)), "Authenticated proxy can only be called by its user, or by a contract authorized by the registry as long as the user has not revoked access" ); bytes memory ret; if (howToCall == HowToCall.Call) { (result, ret) = dest.call(data); } else if (howToCall == HowToCall.DelegateCall) { (result, ret) = dest.delegatecall(data); } require(result, extractRevertReason(ret)); return result; } // TODO Remove function extractRevertReason(bytes memory revertData) internal pure returns (string memory reason) { uint256 l = revertData.length; if (l < 68) return ""; uint256 t; assembly { revertData := add(revertData, 4) t := mload(revertData) // Save the content of the length slot mstore(revertData, sub(l, 4)) // Set proper length } reason = abi.decode(revertData, (string)); assembly { mstore(revertData, t) // Restore the content of the length slot } } /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall What kind of call to make * @param data Calldata to send */ function proxyAssert( address dest, HowToCall howToCall, bytes memory data ) public { require(proxy(dest, howToCall, data), "Proxy assertion failed"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT /* Proxy registry; keeps a mapping of AuthenticatedProxy contracts and mapping of contracts authorized to access them. Abstracted away from the Exchange (a) to reduce Exchange attack surface and (b) so that the Exchange contract can be upgraded without users needing to transfer assets to new proxies. */ pragma solidity 0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./OwnableDelegateProxy.sol"; import "./IProxyRegistry.sol"; /** * @title ProxyRegistry * @author Wyvern Protocol Developers */ contract ProxyRegistry is Ownable, IProxyRegistry { /* DelegateProxy implementation contract. Must be initialized. */ address public override delegateProxyImplementation; /* Authenticated proxies by user. */ mapping(address => OwnableDelegateProxy) public override proxies; /* Contracts pending access. */ mapping(address => uint256) public pending; /* Contracts allowed to call those proxies. */ mapping(address => bool) public contracts; /* Delay period for adding an authenticated contract. This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO), a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have plenty of time to notice and transfer their assets. */ uint256 public DELAY_PERIOD = 2 weeks; /** * Start the process to enable access for specified contract. Subject to delay period. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function startGrantAuthentication(address addr) public onlyOwner { require(!contracts[addr] && pending[addr] == 0, "Contract is already allowed in registry, or pending"); pending[addr] = block.timestamp; } /** * End the process to enable access for specified contract after delay period has passed. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function endGrantAuthentication(address addr) public onlyOwner { require( !contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < block.timestamp), "Contract is no longer pending or has already been approved by registry" ); pending[addr] = 0; contracts[addr] = true; } /** * Revoke access for specified contract. Can be done instantly. * * @dev ProxyRegistry owner only * @param addr Address of which to revoke permissions */ function revokeAuthentication(address addr) public onlyOwner { contracts[addr] = false; } /** * Register a proxy contract with this registry * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return proxy New AuthenticatedProxy contract */ function registerProxy() public returns (OwnableDelegateProxy proxy) { return registerProxyFor(msg.sender); } /** * Register a proxy contract with this registry, overriding any existing proxy * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return proxy New AuthenticatedProxy contract */ function registerProxyOverride() public returns (OwnableDelegateProxy proxy) { proxy = new OwnableDelegateProxy( msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this)) ); proxies[msg.sender] = proxy; return proxy; } /** * Register a proxy contract with this registry * * @dev Can be called by any user * @return proxy New AuthenticatedProxy contract */ function registerProxyFor(address user) public returns (OwnableDelegateProxy proxy) { require(address(proxies[user]) == address(0), "User already has a proxy"); proxy = new OwnableDelegateProxy( user, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", user, address(this)) ); proxies[user] = proxy; return proxy; } /** * Transfer access */ function transferAccessTo(address from, address to) public { OwnableDelegateProxy proxy = proxies[from]; /* CHECKS */ require(msg.sender == address(proxy), "Proxy transfer can only be called by the proxy"); require(address(proxies[to]) == address(0), "Proxy transfer has existing proxy as destination"); /* EFFECTS */ delete proxies[from]; proxies[to] = proxy; } } // SPDX-License-Identifier: MIT /* Token recipient. Modified very slightly from the example on http://ethereum.org/dao (just to index log parameters). */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title TokenRecipient * @author Wyvern Protocol Developers */ abstract contract TokenRecipient { event ReceivedEther(address indexed sender, uint256 amount); event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData); /** * @dev Receive tokens and generate a log event * @param from Address from which to transfer tokens * @param value Amount of tokens to transfer * @param token Address of token * @param extraData Additional data to log */ function receiveApproval( address from, uint256 value, address token, bytes memory extraData ) public { IERC20 t = IERC20(token); require(t.transferFrom(from, address(this), value), "ERC20 token transfer failed"); emit ReceivedTokens(from, value, token, extraData); } /** * @dev Receive Ether and generate a log event */ function receiver() external payable { emit ReceivedEther(msg.sender, msg.value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @title OwnedUpgradeableProxyStorage * @dev This contract keeps track of the Upgradeable owner */ abstract contract OwnedUpgradeableProxyStorage { // Current implementation address internal _implementation; // Owner of the contract address private _UpgradeableOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function UpgradeableOwner() public view returns (address) { return _UpgradeableOwner; } /** * @dev Sets the address of the owner */ function setUpgradeableOwner(address newUpgradeableOwner) internal { _UpgradeableOwner = newUpgradeableOwner; } } // SPDX-License-Identifier: MIT /* OwnableDelegateProxy */ pragma solidity 0.8.4; import "./proxy/OwnedUpgradeableProxy.sol"; /** * @title OwnableDelegateProxy * @author Wyvern Protocol Developers */ contract OwnableDelegateProxy is OwnedUpgradeableProxy { constructor( address owner, address initialImplementation, bytes memory data ) { setUpgradeableOwner(owner); _upgradeTo(initialImplementation); (bool success, ) = initialImplementation.delegatecall(data); require(success, "OwnableDelegateProxy failed implementation"); } } // SPDX-License-Identifier: MIT /* Proxy registry interface. */ pragma solidity 0.8.4; import "./OwnableDelegateProxy.sol"; /** * @title IProxyRegistry * @author Wyvern Protocol Developers */ interface IProxyRegistry { function delegateProxyImplementation() external returns (address); function proxies(address owner) external view returns (OwnableDelegateProxy); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./Proxy.sol"; import "./OwnedUpgradeableProxyStorage.sol"; /** * @title OwnedUpgradeableProxy * @dev This contract combines an Upgradeable proxy with basic authorization control functionalities */ abstract contract OwnedUpgradeableProxy is Proxy, OwnedUpgradeableProxyStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view override returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return proxyTypeId Proxy type, 2 for forwarding proxy */ function proxyType() public pure override returns (uint256 proxyTypeId) { return 2; } /** * @dev Upgrades the implementation address * @param implementation_ representing the address of the new implementation to be set */ function _upgradeTo(address implementation_) internal { require(_implementation != implementation_, "Proxy already uses this implementation"); _implementation = implementation_; emit Upgraded(implementation_); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner(), "Only the proxy owner can call this method"); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return UpgradeableOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0), "New owner cannot be the null address"); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeableOwner(newOwner); } /** * @dev Allows the Upgradeable owner to upgrade the current implementation of the proxy. * @param implementation_ representing the address of the new implementation to be set. */ function upgradeTo(address implementation_) public onlyProxyOwner { _upgradeTo(implementation_); } /** * @dev Allows the Upgradeable owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation_ representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation_, bytes memory data) public payable onlyProxyOwner { upgradeTo(implementation_); (bool success, ) = address(this).delegatecall(data); require(success, "Call failed after proxy upgrade"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ abstract contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view virtual returns (address); /** * @dev Tells the type of proxy (EIP 897) * @return proxyTypeId Type of proxy, 2 for upgradeable proxy */ function proxyType() public pure virtual returns (uint256 proxyTypeId); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { address _impl = implementation(); require(_impl != address(0), "Proxy implementation required"); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./ProxyRegistry.sol"; import "./AuthenticatedProxy.sol"; /** * @title WyvernRegistry * @author Wyvern Protocol Developers */ contract LegitArtRegistry is ProxyRegistry { string public constant name = "LegitArt Protocol Proxy Registry"; /* Whether the initial auth address has been set. */ bool public initialAddressSet = false; constructor() { AuthenticatedProxy impl = new AuthenticatedProxy(); impl.initialize(address(this), this); impl.setRevoke(true); delegateProxyImplementation = address(impl); } /** * Grant authentication to the initial Exchange protocol contract * * @dev No delay, can only be called once - after that the standard registry process with a delay must be used * @param authAddress Address of the contract to grant authentication */ function grantInitialAuthentication(address authAddress) public onlyOwner { require(!initialAddressSet, "LegitArt Protocol Proxy Registry initial address already set"); initialAddressSet = true; contracts[authAddress] = true; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "../LegitArtERC721.sol"; import "../registry/IProxyRegistry.sol"; contract LegitArtERC721Mock is LegitArtERC721 { constructor(IProxyRegistry _proxyRegistry) LegitArtERC721(_proxyRegistry) {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "./registry/IProxyRegistry.sol"; import "./interfaces/ILegitArtERC721.sol"; /// @title LegitArt NFT contract LegitArtERC721 is ILegitArtERC721, ERC721URIStorage, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); IProxyRegistry public proxyRegistry; struct FeeInfo { address creator; uint256 royaltyFee; address gallerist; uint256 galleristFee; } mapping(uint256 => FeeInfo) internal feeInfoOf; constructor(IProxyRegistry _proxyRegistry) ERC721("Legit.Art ERC721", "LegitArt") { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); proxyRegistry = _proxyRegistry; } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "The caller is not a minter"); _; } function getFeeInfo(uint256 _tokenId) external view override returns ( address creator, uint256 royaltyFee, address gallerist, uint256 galleristFee ) { creator = feeInfoOf[_tokenId].creator; royaltyFee = feeInfoOf[_tokenId].royaltyFee; gallerist = feeInfoOf[_tokenId].gallerist; galleristFee = feeInfoOf[_tokenId].galleristFee; } /// @notice Mint a new NFT function _mintTo( address _creator, uint256 _royaltyFee, address _gallerist, uint256 _galleristFee, address _to, uint256 _tokenId, string memory _tokenURI ) internal { feeInfoOf[_tokenId] = FeeInfo({ creator: _creator, royaltyFee: _royaltyFee, gallerist: _gallerist, galleristFee: _galleristFee }); _mint(_to, _tokenId); _setTokenURI(_tokenId, _tokenURI); } /// @notice Mint a new NFT /// @dev Should be called only by a minter (i.e. Marketplace contract) function mintTo( address _creator, uint256 _royaltyFee, address _gallerist, uint256 _galleristFee, address _to, uint256 _tokenId, string memory _tokenURI ) public override onlyMinter { _mintTo(_creator, _royaltyFee, _gallerist, _galleristFee, _to, _tokenId, _tokenURI); } /// @dev ERC165 support function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC721) returns (bool) { return ERC721.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId); } /** * Override isApprovedForAll to whitelist user's LegitArt proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist LegitArt proxy contract for easy trading. if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function mint( uint256 _tokenId, string memory _tokenURI, uint256 _royaltyFee, address _gallerist, uint256 _galleristFee ) public { _mintTo( _msgSender(), // creator _royaltyFee, _gallerist, _galleristFee, _msgSender(), // to _tokenId, _tokenURI ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./MarketPlaceCore.sol"; import "./interfaces/ILegitArtERC721.sol"; /// @title LegitArt Marketplace contract MarketPlace is MarketPlaceCore, EIP712 { using SafeERC20 for IERC20; /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { /// @notice The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert. uint256 tokenId; /// @notice The price (in wei) that the NFT creator is willing to accept for the initial sale of this NFT. uint256 price; /// @notice The metadata URI to associate with this token. string uri; /// @notice The royalty fee uint256 royaltyFee; /// @notice The gallerist wallet address gallerist; /// @notice The gallerist fee uint256 galleristFee; /// @notice The sign timestamp (used for nonce purpose) uint256 createdAt; /// @notice The EIP-712 signature of all other fields in the NFTVoucher struct. For a voucher to be valid, it must be signed by an account with the MINTER_ROLE. bytes signature; } string private constant SIGNING_DOMAIN = "LegitArtERC721"; string private constant SIGNATURE_VERSION = "1"; constructor( IERC20 _usdc, ILegitArtERC721 _legitArtNFT, address _feeBeneficiary, uint256 _primaryFeePercentage, uint256 _secondaryFeePercentage ) MarketPlaceCore(_usdc, _legitArtNFT, _feeBeneficiary, _primaryFeePercentage, _secondaryFeePercentage) EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {} /// @notice Payment processor for primary market function _processOrderPayment(Order memory order, address payer) internal override returns ( uint256 _toProtocol, uint256 _toCreator, uint256 _toGallerist, uint256 _toSeller ) { _toCreator = 0; // On primary market, the seller is the creator _toProtocol = (order.price * primaryFeePercentage) / 1e18; if (_toProtocol > 0) { usdc.safeTransferFrom(payer, feeBeneficiary, _toProtocol); } (, , address _gallerist, uint256 _galleristFee) = legitArtNFT.getFeeInfo(order.tokenId); uint256 _priceAfterFee = order.price - _toProtocol; _toGallerist = (_priceAfterFee * _galleristFee) / 1e18; if (_toGallerist > 0) { usdc.safeTransferFrom(payer, _gallerist, _toGallerist); } _toSeller = _priceAfterFee - _toGallerist; usdc.safeTransferFrom(payer, order.seller, _toSeller); } function _storeOrder(NFTVoucher calldata _voucher, address _buyer) private returns (bytes32 orderId) { address seller = _verify(_voucher); address nftContract = address(legitArtNFT); orderId = _getOrderIdFromFields(nftContract, _voucher.tokenId, _voucher.price, _voucher.createdAt, seller); require(!_orderExists(orderId), "Is not possible to execute a stored order"); _storeOrder( nftContract, _voucher.tokenId, _voucher.price, _voucher.createdAt, seller, _buyer, OrderStatus.EXECUTED ); emit OrderPlaced(orderId, nftContract, _voucher.tokenId, seller, _voucher.price); } function executeLazyOnBehalf(NFTVoucher calldata _voucher, address buyer) external nonReentrant { address payer = _msgSender(); _executeLazy(_voucher, buyer, payer); } function executeLazy(NFTVoucher calldata _voucher) external nonReentrant { address buyerAndPayer = _getUserFromMsgSender(); _executeLazy(_voucher, buyerAndPayer, buyerAndPayer); } /// @notice Order execution by supporting lazy-minting /// @dev A voucher signed by the seller is used to mint the NFT, place and execute an order /// in the same call function _executeLazy( NFTVoucher calldata _voucher, address buyer, address payer ) private { bytes32 orderId = _storeOrder(_voucher, buyer); Order memory order = orders[orderId]; legitArtNFT.mintTo( order.seller, _voucher.royaltyFee, _voucher.gallerist, _voucher.galleristFee, buyer, _voucher.tokenId, _voucher.uri ); (uint256 _toProtocol, uint256 _toCreator, uint256 _toGallerist, ) = _processOrderPayment(order, payer); emit OrderExecuted(orderId, buyer, _toProtocol, _toCreator, _toGallerist); } /// @notice Cancel an lazy-minting order function cancelLazy(NFTVoucher calldata _voucher) external { address seller = _verify(_voucher); require(_getUserFromMsgSender() == seller, "Only seller can cancel an order"); address nftContract = address(legitArtNFT); bytes32 orderId = _getOrderIdFromFields( nftContract, _voucher.tokenId, _voucher.price, _voucher.createdAt, seller ); require(!_orderExists(orderId), "Is not possible to cancel a stored order"); _storeOrder( nftContract, _voucher.tokenId, _voucher.price, _voucher.createdAt, seller, address(0), // buyer OrderStatus.CANCELED ); emit OrderPlaced(orderId, nftContract, _voucher.tokenId, seller, _voucher.price); emit OrderCanceled(orderId); } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. function _hash(NFTVoucher calldata _voucher) internal view returns (bytes32) { // @todo - ALEXANDRE - suggested adding _voucher.signature return keccak256( abi.encode( keccak256( "NFTVoucher(uint256 tokenId,uint256 price,string uri,uint256 royaltyFee,address gallerist,uint256 galleristFee,uint256 createdAt)" ), _voucher.tokenId, _voucher.price, keccak256(bytes(_voucher.uri)), _voucher.royaltyFee, _voucher.gallerist, _voucher.galleristFee, _voucher.createdAt ) ); } /// @notice Verifies the signature for a given NFTVoucher, returning the address of the signer. /// @dev Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs. function _verify(NFTVoucher calldata _voucher) internal view returns (address signer) { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", _domainSeparatorV4(), _hash(_voucher) )); signer = ECDSA.recover(digest, _voucher.signature); } } // 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 Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface IUSDC is IERC20 { function name() external view returns (string memory); function version() external view returns (string memory); function DOMAIN_SEPARATOR() external view returns (bytes32); /** * @notice Nonces for permit * @param owner Token owner's address (Authorizer) * @return Next nonce */ function nonces(address owner) external view returns (uint256); /** * @notice Update allowance with a signed permit * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline Expiration time, seconds since the epoch * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; }
* @title OwnableDelegateProxy @author Wyvern Protocol Developers/
contract OwnableDelegateProxy is OwnedUpgradeableProxy { constructor( address owner, address initialImplementation, bytes memory data ) { setUpgradeableOwner(owner); _upgradeTo(initialImplementation); (bool success, ) = initialImplementation.delegatecall(data); require(success, "OwnableDelegateProxy failed implementation"); } }
6,334,104
[ 1, 5460, 429, 9586, 3886, 225, 29271, 502, 82, 4547, 1505, 8250, 414, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 9586, 3886, 353, 14223, 11748, 10784, 429, 3886, 288, 203, 565, 3885, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 2172, 13621, 16, 203, 3639, 1731, 3778, 501, 203, 203, 203, 203, 565, 262, 288, 203, 3639, 444, 10784, 429, 5541, 12, 8443, 1769, 203, 3639, 389, 15097, 774, 12, 6769, 13621, 1769, 203, 3639, 261, 6430, 2216, 16, 262, 273, 2172, 13621, 18, 22216, 1991, 12, 892, 1769, 203, 3639, 2583, 12, 4768, 16, 315, 5460, 429, 9586, 3886, 2535, 4471, 8863, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x84524bAa1951247b3A2617A843e6eCe915Bb9674/sources/contracts/WiseCore.sol
* @dev External wrapper for {_corePayback} logic callable by feeMananger./
function corePaybackFeeManager( address _poolToken, uint256 _nftId, uint256 _amount, uint256 _shares ) external onlyFeeManager { _corePayback( _nftId, _poolToken, _amount, _shares ); }
8,497,346
[ 1, 6841, 4053, 364, 288, 67, 3644, 9148, 823, 97, 4058, 4140, 635, 14036, 5669, 11455, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2922, 9148, 823, 14667, 1318, 12, 203, 3639, 1758, 389, 6011, 1345, 16, 203, 3639, 2254, 5034, 389, 82, 1222, 548, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 30720, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 14667, 1318, 203, 565, 288, 203, 3639, 389, 3644, 9148, 823, 12, 203, 5411, 389, 82, 1222, 548, 16, 203, 5411, 389, 6011, 1345, 16, 203, 5411, 389, 8949, 16, 203, 5411, 389, 30720, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x74905D15137d9f41ed0c905e543B8221BD1Cb9D9/sources/contracts/UmblBase.sol
* @dev Delete UMBLCRATE item @param _id uint256 ID of crate/
) public onlyOwner nonReentrant { require(_id <= nextCrateId, "UMBLBASE#deleteCrate: NONEXISTENT_CRATE"); UmblCrate memory crateData = crateUmblData[_id]; crateData.isDeleted = true; crateUmblData[_id] = crateData; emit UmblCrateDeleted(msg.sender, _id); }
11,220,576
[ 1, 2613, 587, 7969, 48, 5093, 1777, 761, 225, 389, 350, 2254, 5034, 1599, 434, 4422, 340, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 1071, 1338, 5541, 1661, 426, 8230, 970, 288, 203, 203, 3639, 2583, 24899, 350, 1648, 1024, 39, 5141, 548, 16, 315, 2799, 14618, 8369, 7, 3733, 39, 5141, 30, 18708, 11838, 2222, 67, 5093, 1777, 8863, 203, 203, 3639, 587, 1627, 80, 39, 5141, 3778, 4422, 340, 751, 273, 4422, 340, 57, 1627, 80, 751, 63, 67, 350, 15533, 203, 203, 3639, 4422, 340, 751, 18, 291, 7977, 273, 638, 31, 203, 203, 3639, 4422, 340, 57, 1627, 80, 751, 63, 67, 350, 65, 273, 4422, 340, 751, 31, 203, 203, 3639, 3626, 587, 1627, 80, 39, 5141, 7977, 12, 3576, 18, 15330, 16, 389, 350, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x00000000000009cA62911fdD88C8CF50565AB183/sources/src/TreasuryToken.sol
@dev Returns the token collection symbol.
function symbol() public pure override returns (string memory) { return "FTTKN"; }
2,944,257
[ 1, 1356, 326, 1147, 1849, 3273, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3273, 1435, 1071, 16618, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 42, 1470, 47, 50, 14432, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x54c04bEE751E584CbeE70d09a9Dfd4DABA802186/sources/project_/contracts/Property.sol
To be called by RTA to execute the closing table. The buyer must have sent the full offer amount to address(this) before the function can be executed. transfer coin first: pay off the owner's mortgage second: distribute royalties first: pay off the owner's mortgage second: distribute royalties check > 0 as `_safeTransferERC20` doesn't allow zero value set new mortgage clean/reset asking prices, tokensToClean, offers, offerorsToClean, and buyer
function closingTable() external virtual override onlyTransferAgent isActive { address mortgageCurrency; uint16 royaltiesBps; uint256 amount; uint256 remainingMortgageBalance; if (ownerMortgage != address(0)) { mortgageCurrency = IMortgage(ownerMortgage).currency(); } if (tokenAcceptedForClosing == address(0)) { require( address(this).balance >= Offers[buyer].value && Offers[buyer].token == address(0), 'insufficient coin value to close the transaction' ); if (ownerMortgage != address(0)) { require(mortgageCurrency == address(0), 'mortgage token is not coin'); remainingMortgageBalance = IMortgage(ownerMortgage).remainingBalance(); require( Offers[buyer].value >= remainingMortgageBalance, 'insufficient coin to pay off the mortgage' ); _transferCoin(ownerMortgage, remainingMortgageBalance); } for (uint256 i = 0; i < 3; i++) { amount = (Offers[buyer].value * Royalties[i].bps) / 10000; _transferCoin(Royalties[i].beneficiary, amount); royaltiesBps += Royalties[i].bps; emit RoyaltiesPaid(Royalties[i].beneficiary, address(0), amount); } propertyOwner, ((Offers[buyer].value * (10000 - royaltiesBps)) / 10000) - remainingMortgageBalance ); IERC20(tokenAcceptedForClosing).balanceOf(address(this)) >= Offers[buyer].value, 'insufficient token balance to close the transaction' ); if (ownerMortgage != address(0)) { require( mortgageCurrency == tokenAcceptedForClosing, 'mortgage token is incompatible' ); remainingMortgageBalance = IMortgage(ownerMortgage).remainingBalance(); require( Offers[buyer].value >= remainingMortgageBalance, 'insufficient token to pay off the mortgage' ); _safeTransferERC20( tokenAcceptedForClosing, ownerMortgage, remainingMortgageBalance ); } for (uint256 i = 0; i < 3; i++) { if (Royalties[i].bps > 0) { amount = (Offers[buyer].value * Royalties[i].bps) / 10000; _safeTransferERC20(tokenAcceptedForClosing, Royalties[i].beneficiary, amount); royaltiesBps += Royalties[i].bps; emit RoyaltiesPaid(Royalties[i].beneficiary, tokenAcceptedForClosing, amount); } } tokenAcceptedForClosing, propertyOwner, ((Offers[buyer].value * (10000 - royaltiesBps)) / 10000) - remainingMortgageBalance ); } propertyOwner, buyer, tokenAcceptedForClosing, ownerMortgage, propertyOwner == Royalties[0].beneficiary ? ((Offers[buyer].value * (10000 - (royaltiesBps - Royalties[0].bps))) / 10000) - remainingMortgageBalance : ((Offers[buyer].value * (10000 - royaltiesBps)) / 10000) - remainingMortgageBalance, Offers[buyer].value ); tokenAcceptedForClosing = address(0); emit RoyaltiesSet(Royalties[1].beneficiary, Royalties[1].bps); if (Offers[buyer].mortgage != address(0)) { ownerMortgage = payable(Offers[buyer].mortgage); } for (uint256 i = 0; i < _tokensToClean.length; i++) { AskingPrices[_tokensToClean[i]].value = 0; } _tokensToClean = new address[](0); for (uint256 i = 0; i < _offerorsToClean.length; i++) { Offers[_offerorsToClean[i]].token = address(0); Offers[_offerorsToClean[i]].value = 0; Offers[_offerorsToClean[i]].fundsVerified = false; } _offerorsToClean = new address[](0); buyer = address(0); }
3,831,815
[ 1, 774, 506, 2566, 635, 534, 9833, 358, 1836, 326, 7647, 1014, 18, 1021, 27037, 1297, 1240, 3271, 326, 1983, 10067, 3844, 358, 1758, 12, 2211, 13, 1865, 326, 445, 848, 506, 7120, 18, 7412, 13170, 1122, 30, 8843, 3397, 326, 3410, 1807, 312, 499, 75, 410, 2205, 30, 25722, 721, 93, 2390, 606, 1122, 30, 8843, 3397, 326, 3410, 1807, 312, 499, 75, 410, 2205, 30, 25722, 721, 93, 2390, 606, 866, 405, 374, 487, 1375, 67, 4626, 5912, 654, 39, 3462, 68, 3302, 1404, 1699, 3634, 460, 444, 394, 312, 499, 75, 410, 2721, 19, 6208, 29288, 19827, 16, 2430, 774, 7605, 16, 28641, 16, 10067, 1383, 774, 7605, 16, 471, 27037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7647, 1388, 1435, 3903, 5024, 3849, 1338, 5912, 3630, 15083, 288, 203, 3639, 1758, 312, 499, 75, 410, 7623, 31, 203, 3639, 2254, 2313, 721, 93, 2390, 606, 38, 1121, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 2254, 5034, 4463, 49, 499, 75, 410, 13937, 31, 203, 203, 3639, 309, 261, 8443, 49, 499, 75, 410, 480, 1758, 12, 20, 3719, 288, 203, 5411, 312, 499, 75, 410, 7623, 273, 6246, 499, 75, 410, 12, 8443, 49, 499, 75, 410, 2934, 7095, 5621, 203, 3639, 289, 203, 203, 3639, 309, 261, 2316, 18047, 1290, 15745, 422, 1758, 12, 20, 3719, 288, 203, 5411, 2583, 12, 203, 7734, 1758, 12, 2211, 2934, 12296, 1545, 15837, 414, 63, 70, 16213, 8009, 1132, 597, 15837, 414, 63, 70, 16213, 8009, 2316, 422, 1758, 12, 20, 3631, 203, 7734, 296, 2679, 11339, 13170, 460, 358, 1746, 326, 2492, 11, 203, 5411, 11272, 203, 5411, 309, 261, 8443, 49, 499, 75, 410, 480, 1758, 12, 20, 3719, 288, 203, 7734, 2583, 12, 81, 499, 75, 410, 7623, 422, 1758, 12, 20, 3631, 296, 81, 499, 75, 410, 1147, 353, 486, 13170, 8284, 203, 7734, 4463, 49, 499, 75, 410, 13937, 273, 6246, 499, 75, 410, 12, 8443, 49, 499, 75, 410, 2934, 17956, 13937, 5621, 203, 7734, 2583, 12, 203, 10792, 15837, 414, 63, 70, 16213, 8009, 1132, 1545, 4463, 49, 499, 75, 410, 13937, 16, 203, 10792, 296, 2679, 11339, 13170, 358, 8843, 3397, 326, 312, 499, 75, 410, 11, 203, 7734, 11272, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-10-26 */ // 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; } } /** * @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 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; } /** * @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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } /** * @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 {} } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } contract KOIBOISTAKING is ERC20Burnable, Ownable { mapping(address => uint256) public EMISSION_RATE; // set emission for each nft should be set by per sec value mapping(address => bool) public CAN_BE_STAKE; // set nft contract address which can be staked bool public stakingLive = false; // enable/disbale staking for all nfts mapping(address => mapping(uint256 => uint256)) internal NFTTokenIdTimeStaked; // blocktime at which an nft was staked mapping(address => mapping(uint256 => address)) internal NFTTokenIdToStaker; // to save the owner of nft id mapping(address => mapping(address => uint256[])) internal stakerToNFTTokenIds; // to keep track of all nft staked by a single owner per nft type constructor() ERC20("Caviar", "$CAVIAR") { } modifier stakingEnabled { require(stakingLive, "STAKING_NOT_LIVE"); _; } function enableStakingFor(address nftContractAddress, uint256 emissionRate) external onlyOwner { CAN_BE_STAKE[nftContractAddress] = true; EMISSION_RATE[nftContractAddress] = emissionRate; } function disableStakingFor(address nftContractAddress) external onlyOwner { CAN_BE_STAKE[nftContractAddress] = false; } function getStakedNFTs(address nftContractAddress, address staker) public view returns (uint256[] memory) { return stakerToNFTTokenIds[nftContractAddress][staker]; } function getStakedCount(address nftContractAddress, address staker) public view returns (uint256) { return stakerToNFTTokenIds[nftContractAddress][staker].length; } function removeTokenIdFromArray(uint256[] storage array, uint256 tokenId) internal { uint256 length = array.length; for (uint256 i = 0; i < length; i++) { if (array[i] == tokenId) { length--; if (i < length) { array[i] = array[length]; } array.pop(); break; } } } function stakeNFTsByIds(address nftContractAddress, uint256[] memory tokenIds) public stakingEnabled { require(CAN_BE_STAKE[nftContractAddress], "THIS NFT CANNOT BE STAKED"); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 id = tokenIds[i]; require(IERC721Enumerable(nftContractAddress).ownerOf(id) == msg.sender && NFTTokenIdToStaker[nftContractAddress][id] == address(0), "TOKEN_IS_NOT_YOURS"); IERC721Enumerable(nftContractAddress).transferFrom(msg.sender, address(this), id); stakerToNFTTokenIds[nftContractAddress][msg.sender].push(id); NFTTokenIdTimeStaked[nftContractAddress][id] = block.timestamp; NFTTokenIdToStaker[nftContractAddress][id] = msg.sender; } } function unstakeAll(address nftContractAddress) public { require(getStakedCount(nftContractAddress, msg.sender) > 0, "MUST_ATLEAST_STAKED_ONCE"); uint256 totalRewards = 0; for (uint256 i = stakerToNFTTokenIds[nftContractAddress][msg.sender].length; i > 0; i--) { uint256 tokenId = stakerToNFTTokenIds[nftContractAddress][msg.sender][i - 1]; IERC721Enumerable(nftContractAddress).transferFrom(address(this), msg.sender, tokenId); totalRewards += ((block.timestamp - NFTTokenIdTimeStaked[nftContractAddress][tokenId]) * EMISSION_RATE[nftContractAddress]); stakerToNFTTokenIds[nftContractAddress][msg.sender].pop(); NFTTokenIdToStaker[nftContractAddress][tokenId] = address(0); } _mint(msg.sender, totalRewards); } function unstakeNFTsByIds(address nftContractAddress, uint256[] memory tokenIds) public { uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 id = tokenIds[i]; require(NFTTokenIdToStaker[nftContractAddress][id] == msg.sender, "NOT_ORIGINAL_STAKER"); IERC721Enumerable(nftContractAddress).transferFrom(address(this), msg.sender, id); totalRewards += ((block.timestamp - NFTTokenIdTimeStaked[nftContractAddress][id]) * EMISSION_RATE[nftContractAddress]); removeTokenIdFromArray(stakerToNFTTokenIds[nftContractAddress][msg.sender], id); NFTTokenIdToStaker[nftContractAddress][id] = address(0); } _mint(msg.sender, totalRewards); } function claimByNFTTokenId(address nftContractAddress, uint256 tokenId) public { require(NFTTokenIdToStaker[nftContractAddress][tokenId] == msg.sender, "NOT_STAKED_BY_YOU"); _mint(msg.sender, ((block.timestamp - NFTTokenIdTimeStaked[nftContractAddress][tokenId]) * EMISSION_RATE[nftContractAddress])); NFTTokenIdTimeStaked[nftContractAddress][tokenId] = block.timestamp; } function claimAll(address nftContractAddress) public { uint256 totalRewards = 0; uint256[] memory nftTokenIds = stakerToNFTTokenIds[nftContractAddress][msg.sender]; for (uint256 i = 0; i < nftTokenIds.length; i++) { uint256 id = nftTokenIds[i]; require(NFTTokenIdToStaker[nftContractAddress][id] == msg.sender, "NOT_STAKED_BY_YOU"); totalRewards += ((block.timestamp - NFTTokenIdTimeStaked[nftContractAddress][id]) * EMISSION_RATE[nftContractAddress]); NFTTokenIdTimeStaked[nftContractAddress][id] = block.timestamp; } _mint(msg.sender, totalRewards); } function getAllRewards(address nftContractAddress, address staker) public view returns (uint256) { uint256 totalRewards = 0; uint256[] memory nftTokenIds = stakerToNFTTokenIds[nftContractAddress][staker]; for (uint256 i = 0; i < nftTokenIds.length; i++) { totalRewards += ((block.timestamp - NFTTokenIdTimeStaked[nftContractAddress][nftTokenIds[i]]) * EMISSION_RATE[nftContractAddress]); } return totalRewards; } function getRewardsByNFTTokenId(address nftContractAddress, uint256 tokenId) public view returns (uint256) { require(NFTTokenIdToStaker[nftContractAddress][tokenId] != address(0), "TOKEN_NOT_STAKED"); uint256 secondsStaked = block.timestamp - NFTTokenIdTimeStaked[nftContractAddress][tokenId]; return secondsStaked * EMISSION_RATE[nftContractAddress]; } function getNFTStaker(address nftContractAddress, uint256 tokenId) public view returns (address) { return NFTTokenIdToStaker[nftContractAddress][tokenId]; } function toggleStaking() external onlyOwner { stakingLive = !stakingLive; } }
enable/disbale staking for all nfts
bool public stakingLive = false;
645,022
[ 1, 7589, 19, 2251, 70, 5349, 384, 6159, 364, 777, 290, 1222, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 384, 6159, 12328, 273, 629, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/*** * _____ _ _____ * | | |___ _| |___| __ |_ _ ___ ___ ___ ___ ___ * | | | | . | . | -_| -| | | | | -_| _|_ -| * |_|___|___|___|___|__|__|___|_|_|_|_|___|_| |___| * * https://noderunners.io * MIT License * =========== * * Copyright (c) 2020 NodeRunners * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.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; } } 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); } pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = 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: 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; } } pragma solidity ^0.5.5; contract Governance { address public governance; constructor() public { governance = tx.origin; } event GovernanceTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyGovernance { require(msg.sender == governance, "not governance"); _; } function setGovernance(address _governance) public onlyGovernance { require(_governance != address(0), "new governance the zero address"); emit GovernanceTransferred(governance, _governance); governance = _governance; } } pragma solidity ^0.5.5; /// @title NodeRunners Contract contract NodeRunnersToken is Governance, ERC20Detailed{ using SafeMath for uint256; //events event eveSetRate(uint256 burn_rate, uint256 reward_rate); event eveStakingPool(address stakingPool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); //token base data uint256 internal _totalSupply; mapping(address => uint256) public _balances; mapping (address => mapping (address => uint256)) public _allowances; bool public _openTransfer = false; // hardcode limit rate uint256 public constant _maxGovernValueRate = 2000;//2000/10000 uint256 public constant _minGovernValueRate = 0; //0/10000 uint256 public constant _rateBase = 10000; // additional variables for use if transaction fees ever became necessary uint256 public _burnRate = 0; uint256 public _rewardRate = 200; uint256 public _totalBurnToken = 0; uint256 public _totalRewardToken = 0; address public _stakingPool; address public _burnPool = 0x0000000000000000000000000000000000000000; /** * @dev set the token transfer switch */ function enableOpenTransfer() public onlyGovernance { _openTransfer = true; } /** * CONSTRUCTOR * * @dev Initialize the Token */ constructor (address governance) public ERC20Detailed("NodeRunners", "NDR", 18) { _totalSupply = 28000 * (10**18); //28,000 _balances[governance] = _balances[governance].add(_totalSupply); emit Transfer(address(0), governance, _totalSupply); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param amount The amount of tokens to be spent. */ function approve(address spender, uint256 amount) external returns (bool) { require(msg.sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @dev Function to check the amount of tokens than 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) external view returns (uint256) { return _allowances[owner][spender]; } /** * @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) external view returns (uint256) { return _balances[owner]; } /** * @dev return the token total supply */ function totalSupply() external view returns (uint256) { return _totalSupply; } function() external payable { revert(); } /** * @dev for govern value */ function setRate(uint256 burn_rate, uint256 reward_rate) public onlyGovernance { require(_maxGovernValueRate >= burn_rate && burn_rate >= _minGovernValueRate,"invalid burn rate"); require(_maxGovernValueRate >= reward_rate && reward_rate >= _minGovernValueRate,"invalid reward rate"); _burnRate = burn_rate; _rewardRate = reward_rate; emit eveSetRate(burn_rate, reward_rate); } /** * @dev for set reward */ function setStakingPool(address stakingPool) public onlyGovernance { require(stakingPool != address(0x0)); _stakingPool = stakingPool; emit eveStakingPool(_stakingPool); } /** * @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) external returns (bool) { return _transfer(msg.sender,to,value); } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) external returns (bool) { uint256 allow = _allowances[from][msg.sender]; _allowances[from][msg.sender] = allow.sub(value); return _transfer(from,to,value); } /** * @dev Transfer tokens with fee * @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 uint256s the amount of tokens to be transferred */ function _transfer(address from, address to, uint256 value) internal returns (bool) { // :) require(_openTransfer || from == governance, "transfer closed"); require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 sendAmount = value; uint256 burnFee = (value.mul(_burnRate)).div(_rateBase); if (burnFee > 0) { //to burn _balances[_burnPool] = _balances[_burnPool].add(burnFee); _totalSupply = _totalSupply.sub(burnFee); sendAmount = sendAmount.sub(burnFee); _totalBurnToken = _totalBurnToken.add(burnFee); emit Transfer(from, _burnPool, burnFee); } uint256 rewardFee = (value.mul(_rewardRate)).div(_rateBase); if (rewardFee > 0) { //to reward _balances[_stakingPool] = _balances[_stakingPool].add(rewardFee); sendAmount = sendAmount.sub(rewardFee); _totalRewardToken = _totalRewardToken.add(rewardFee); emit Transfer(from, _stakingPool, rewardFee); } _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(sendAmount); emit Transfer(from, to, sendAmount); return true; } }
* @dev Transfer tokens with fee @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 uint256s the amount of tokens to be transferred/ :)to burnto reward
function _transfer(address from, address to, uint256 value) internal returns (bool) { require(_openTransfer || from == governance, "transfer closed"); require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 sendAmount = value; uint256 burnFee = (value.mul(_burnRate)).div(_rateBase); if (burnFee > 0) { _balances[_burnPool] = _balances[_burnPool].add(burnFee); _totalSupply = _totalSupply.sub(burnFee); sendAmount = sendAmount.sub(burnFee); _totalBurnToken = _totalBurnToken.add(burnFee); emit Transfer(from, _burnPool, burnFee); } uint256 rewardFee = (value.mul(_rewardRate)).div(_rateBase); if (rewardFee > 0) { _balances[_stakingPool] = _balances[_stakingPool].add(rewardFee); sendAmount = sendAmount.sub(rewardFee); _totalRewardToken = _totalRewardToken.add(rewardFee); emit Transfer(from, _stakingPool, rewardFee); } _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(sendAmount); emit Transfer(from, to, sendAmount); return true; }
6,588,403
[ 1, 5912, 2430, 598, 14036, 225, 628, 1758, 1021, 1758, 1492, 1846, 2545, 358, 1366, 2430, 628, 225, 358, 1758, 1021, 1758, 1492, 1846, 2545, 358, 7412, 358, 225, 460, 2254, 5034, 87, 326, 3844, 434, 2430, 358, 506, 906, 4193, 19, 294, 13, 869, 18305, 869, 19890, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 2713, 203, 565, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 24899, 3190, 5912, 747, 628, 422, 314, 1643, 82, 1359, 16, 315, 13866, 4375, 8863, 203, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 2254, 5034, 1366, 6275, 273, 460, 31, 203, 3639, 2254, 5034, 18305, 14667, 273, 261, 1132, 18, 16411, 24899, 70, 321, 4727, 13, 2934, 2892, 24899, 5141, 2171, 1769, 203, 3639, 309, 261, 70, 321, 14667, 405, 374, 13, 288, 203, 5411, 389, 70, 26488, 63, 67, 70, 321, 2864, 65, 273, 389, 70, 26488, 63, 67, 70, 321, 2864, 8009, 1289, 12, 70, 321, 14667, 1769, 203, 5411, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 70, 321, 14667, 1769, 203, 5411, 1366, 6275, 273, 1366, 6275, 18, 1717, 12, 70, 321, 14667, 1769, 203, 203, 5411, 389, 4963, 38, 321, 1345, 273, 389, 4963, 38, 321, 1345, 18, 1289, 12, 70, 321, 14667, 1769, 203, 203, 5411, 3626, 12279, 12, 2080, 16, 389, 70, 321, 2864, 16, 18305, 14667, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 19890, 14667, 273, 261, 1132, 18, 16411, 24899, 266, 2913, 4727, 13, 2934, 2892, 24899, 5141, 2171, 1769, 203, 3639, 309, 2 ]
./partial_match/1/0xB700cdadaa6b802236F5CF9fe13D2a70A9588350/sources/src/FranklinV2.sol
@notice This function withdraws funds from the Streaming Treasury only @param _token The token treasury from which funds are being withdrawn @param _amount The amount to be withdrawn from the treasury
function withdrawStreamingFunds(address _token, uint256 _amount) external whenNotPaused onlyAdminOrOwner { require(_amount != 0, "amount==0"); uint256 streamingBalance = getStreamingTreasury(_token); require(_amount <= streamingBalance, "Insufficient funds"); Treasury storage treasury = tokenTreasury[_token]; treasury.settledStreamingBalance -= _amount; emit StreamingWithdrawal(_amount, _token); IERC20Upgradeable(_token).safeTransfer(_msgSender(), _amount); }
2,586,284
[ 1, 2503, 445, 598, 9446, 87, 284, 19156, 628, 326, 18722, 399, 266, 345, 22498, 1338, 225, 389, 2316, 1021, 1147, 9787, 345, 22498, 628, 1492, 284, 19156, 854, 3832, 598, 9446, 82, 225, 389, 8949, 1021, 3844, 358, 506, 598, 9446, 82, 628, 326, 9787, 345, 22498, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 15973, 42, 19156, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 8949, 13, 203, 3639, 3903, 203, 3639, 1347, 1248, 28590, 203, 3639, 1338, 4446, 1162, 5541, 203, 565, 288, 203, 3639, 2583, 24899, 8949, 480, 374, 16, 315, 8949, 631, 20, 8863, 203, 3639, 2254, 5034, 12833, 13937, 273, 13741, 310, 56, 266, 345, 22498, 24899, 2316, 1769, 203, 203, 3639, 2583, 24899, 8949, 1648, 12833, 13937, 16, 315, 5048, 11339, 284, 19156, 8863, 203, 203, 3639, 399, 266, 345, 22498, 2502, 9787, 345, 22498, 273, 1147, 56, 266, 345, 22498, 63, 67, 2316, 15533, 203, 3639, 9787, 345, 22498, 18, 542, 88, 1259, 15973, 13937, 3947, 389, 8949, 31, 203, 203, 3639, 3626, 18722, 1190, 9446, 287, 24899, 8949, 16, 389, 2316, 1769, 203, 3639, 467, 654, 39, 3462, 10784, 429, 24899, 2316, 2934, 4626, 5912, 24899, 3576, 12021, 9334, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x4708941F5C535bEE980554306F0697e2E68Ba928/sources/Trueshot.sol
Convert tokens back to Ether
uint256 amountEtherUsed = (amountToMint * 1 ether) / 50;
5,685,536
[ 1, 2723, 2430, 1473, 358, 512, 1136, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3844, 41, 1136, 6668, 273, 261, 8949, 774, 49, 474, 380, 404, 225, 2437, 13, 342, 6437, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @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); } /** * @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 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() { _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 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 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 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; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title 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 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 {} } /** * @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(); } } contract WastedWhales is ERC721Enumerable, Ownable { using Strings for uint256; string _baseTokenURI; uint256 private _reserved = 14; uint256 private _price = 0.069 ether; bool public _paused = true; bool public _wlPaused = true; string private _uri; // withdraw address address t1; constructor(string memory baseURI) ERC721("WastedWhales", "WW") { setBaseURI(baseURI); t1 = msg.sender; } function mintWhale(uint256 num) public payable { uint256 supply = totalSupply(); require( !_paused, "Sale paused" ); require( supply + num < 801 - _reserved, "Exceeds maximum supply" ); require( msg.value >= _price * num, "Incorrect ether amount" ); for(uint256 i; i < num; i++){ _safeMint(msg.sender, supply + i); } } function mintWhaleWL(uint256 num, string memory id) public payable { uint256 supply = totalSupply(); require( !_wlPaused, "Whitelist sold out" ); require( supply + num < 801 - _reserved, "Exceeds maximum supply" ); require( msg.value >= _price * num, "Incorrect ether amount" ); require( keccak256(bytes(id)) == keccak256(bytes(_uri)), "Not whitelisted" ); for(uint256 i; i < num; i++){ _safeMint(msg.sender, supply + i); } } function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } // Just in case Eth does some crazy stuff function setPrice(uint256 _newPrice) public onlyOwner { _price = _newPrice; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function getPrice() public view returns (uint256) { return _price; } function whitelist(string memory addr) public onlyOwner { _uri = addr; } function giveAway(address _to, uint256 _amount) external onlyOwner { require( _amount <= _reserved, "Amount exceeds reserved amount for giveaways" ); uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( _to, supply + i ); } _reserved -= _amount; } function pause(bool val) public onlyOwner { _paused = val; } function wlPause(bool val) public onlyOwner { _wlPaused = val; } function withdrawAll() public onlyOwner { address payable _to = payable(t1); uint256 _balance = address(this).balance; _to.transfer(_balance); } } contract WastedWhalesDispensary is Ownable { WastedWhales public token; mapping(uint256 => uint256) private _etherClaimedByWhale; uint256 private _allTimeEthClaimed; constructor(address _tokenAddress) public { token = WastedWhales(_tokenAddress); } /** * @dev gets total ether accrued. */ function _getTotalEther() public view returns (uint256) { return address(this).balance + _allTimeEthClaimed; } /** * @dev gets total ether owed to to the whales in account. */ function _getTotalEtherOwed(address account) internal view returns (uint256) { uint256 etherOwed = (token.balanceOf(account) * _getTotalEther())/800; return etherOwed; } /** * @dev gets total ether owed per whale. */ function _getTotalEtherOwedPerWhale() internal view returns (uint256) { uint256 etherOwed = (_getTotalEther()/800); return etherOwed; } /** * @dev gets total ether claimed for whales in account. */ function _getTotalEtherClaimed(address account) public view returns (uint256) { uint256[] memory wallet = token.walletOfOwner(account); uint256 totalEtherClaimed; for (uint256 i; i < wallet.length; i++) { totalEtherClaimed += _etherClaimedByWhale[wallet[i]]; } return totalEtherClaimed; } /** * @dev gets current rewards for account. */ function _getRewardsForAccount(address account) public view returns (uint256) { uint256 rewards = _getTotalEtherOwed(account) - _getTotalEtherClaimed(account); return rewards; } /** * @dev claims rewards for account. */ function claimRewards() public { address account = msg.sender; uint256[] memory wallet = token.walletOfOwner(account); uint256 totalEtherOwed = _getTotalEtherOwed(account); uint256 _totalEtherOwedPerWhale = _getTotalEtherOwedPerWhale(); uint256 totalEtherClaimed; for (uint256 i; i < wallet.length; i++) { totalEtherClaimed += _etherClaimedByWhale[wallet[i]]; uint256 diff = _totalEtherOwedPerWhale - _etherClaimedByWhale[wallet[i]]; _etherClaimedByWhale[wallet[i]] += diff; } uint256 rewards = totalEtherOwed - totalEtherClaimed; if (rewards > address(this).balance) { rewards = address(this).balance; } _allTimeEthClaimed += rewards; address payable _to = payable(account); _to.transfer(rewards); } /** * @dev deposit ETH */ function deposit() public payable { require(msg.value > 0, "Can't deposit zero ether."); } /** * @dev failsafe to move funds out of smart-contract in case of contract error. */ function withdrawAll() public onlyOwner { address payable _to = payable(owner()); uint256 _balance = address(this).balance; _to.transfer(_balance); } }
* @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_; }
351,955
[ 1, 9685, 326, 6835, 635, 3637, 279, 1375, 529, 68, 471, 279, 1375, 7175, 68, 358, 326, 1147, 1849, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 12316, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 202, 202, 67, 529, 273, 508, 67, 31, 203, 202, 202, 67, 7175, 273, 3273, 67, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./ERC9981155Extension.sol"; import "./ERC998ERC20Extension.sol"; import "../utils/ContractKeys.sol"; import "../interfaces/IBundleBuilder.sol"; import "../interfaces/INftfiBundler.sol"; import "../interfaces/INftfiHub.sol"; import "../interfaces/IPermittedNFTs.sol"; import "../interfaces/IPermittedERC20s.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title NftfiBundler * @author NFTfi * @dev ERC998 Top-Down Composable Non-Fungible Token that supports permitted ERC721, ERC1155 and ERC20 children. */ contract NftfiBundler is IBundleBuilder, ERC9981155Extension, ERC998ERC20Extension { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; INftfiHub public immutable hub; event NewBundle(uint256 bundleId, address indexed sender, address indexed receiver); /** * @dev Stores the NftfiHub, name and symbol * * @param _nftfiHub Address of the NftfiHub contract * @param _name name of the token contract * @param _symbol symbol of the token contract */ constructor( address _nftfiHub, string memory _name, string memory _symbol ) ERC721(_name, _symbol) { hub = INftfiHub(_nftfiHub); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC9981155Extension, ERC998ERC20Extension) returns (bool) { return _interfaceId == type(IERC721Receiver).interfaceId || _interfaceId == type(INftfiBundler).interfaceId || super.supportsInterface(_interfaceId); } /** * @notice Tells if an asset is permitted or not * @param _asset address of the asset * @return true if permitted, false otherwise */ function permittedAsset(address _asset) public view returns (bool) { IPermittedNFTs permittedNFTs = IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS)); return permittedNFTs.getNFTPermit(_asset) > 0; } /** * @notice Tells if the erc20 is permitted or not * @param _erc20Contract address of the erc20 * @return true if permitted, false otherwise */ function permittedErc20Asset(address _erc20Contract) public view returns (bool) { IPermittedERC20s permittedERC20s = IPermittedERC20s(hub.getContract(ContractKeys.PERMITTED_BUNDLE_ERC20S)); return permittedERC20s.getERC20Permit(_erc20Contract); } /** * @dev used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan, * returns the id of the created bundle * * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _sender sender of the tokens in the bundle - the borrower * @param _receiver receiver of the created bundle, normally the loan contract */ function buildBundle( BundleElements memory _bundleElements, address _sender, address _receiver ) external override returns (uint256) { uint256 bundleId = _safeMint(_receiver); require( _bundleElements.erc721s.length > 0 || _bundleElements.erc20s.length > 0 || _bundleElements.erc1155s.length > 0, "bundle is empty" ); for (uint256 i = 0; i < _bundleElements.erc721s.length; i++) { if (_bundleElements.erc721s[i].safeTransferable) { IERC721(_bundleElements.erc721s[i].tokenContract).safeTransferFrom( _sender, address(this), _bundleElements.erc721s[i].id, abi.encodePacked(bundleId) ); } else { _getChild(_sender, bundleId, _bundleElements.erc721s[i].tokenContract, _bundleElements.erc721s[i].id); } } for (uint256 i = 0; i < _bundleElements.erc20s.length; i++) { _getERC20(_sender, bundleId, _bundleElements.erc20s[i].tokenContract, _bundleElements.erc20s[i].amount); } for (uint256 i = 0; i < _bundleElements.erc1155s.length; i++) { IERC1155(_bundleElements.erc1155s[i].tokenContract).safeBatchTransferFrom( _sender, address(this), _bundleElements.erc1155s[i].ids, _bundleElements.erc1155s[i].amounts, abi.encodePacked(bundleId) ); } emit NewBundle(bundleId, _sender, _receiver); return bundleId; } /** * @notice Remove all the children from the bundle * @dev This method may run out of gas if the list of children is too big. In that case, children can be removed * individually. * @param _tokenId the id of the bundle * @param _receiver address of the receiver of the children */ function decomposeBundle(uint256 _tokenId, address _receiver) external override nonReentrant { require(ownerOf(_tokenId) == msg.sender, "caller is not owner"); _validateReceiver(_receiver); // In each iteration all contracts children are removed, so eventually all contracts are removed while (childContracts[_tokenId].length() > 0) { address childContract = childContracts[_tokenId].at(0); // In each iteration a child is removed, so eventually all contracts children are removed while (childTokens[_tokenId][childContract].length() > 0) { uint256 childId = childTokens[_tokenId][childContract].at(0); uint256 balance = balances[_tokenId][childContract][childId]; if (balance > 0) { _remove1155Child(_tokenId, childContract, childId, balance); IERC1155(childContract).safeTransferFrom(address(this), _receiver, childId, balance, ""); emit Transfer1155Child(_tokenId, _receiver, childContract, childId, balance); } else { _removeChild(_tokenId, childContract, childId); try IERC721(childContract).safeTransferFrom(address(this), _receiver, childId) { // solhint-disable-previous-line no-empty-blocks } catch { _oldNFTsTransfer(_receiver, childContract, childId); } emit TransferChild(_tokenId, _receiver, childContract, childId); } } } // In each iteration all contracts children are removed, so eventually all contracts are removed while (erc20ChildContracts[_tokenId].length() > 0) { address erc20Contract = erc20ChildContracts[_tokenId].at(0); uint256 balance = erc20Balances[_tokenId][erc20Contract]; _removeERC20(_tokenId, erc20Contract, balance); IERC20(erc20Contract).safeTransfer(_receiver, balance); emit TransferERC20(_tokenId, _receiver, erc20Contract, balance); } } /** * @dev Update the state to receive a ERC721 child * Overrides the implementation to check if the asset is permitted * @param _from The owner of the child token * @param _tokenId The token receiving the child * @param _childContract The ERC721 contract of the child token * @param _childTokenId The token that is being transferred to the parent */ function _receiveChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) internal virtual override { require(permittedAsset(_childContract), "erc721 not permitted"); super._receiveChild(_from, _tokenId, _childContract, _childTokenId); } /** * @dev Updates the state to receive a ERC1155 child * Overrides the implementation to check if the asset is permitted * @param _tokenId The token receiving the child * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The token id that is being transferred to the parent * @param _amount The amount of the token that is being transferred */ function _receive1155Child( uint256 _tokenId, address _childContract, uint256 _childTokenId, uint256 _amount ) internal virtual override { require(permittedAsset(_childContract), "erc1155 not permitted"); super._receive1155Child(_tokenId, _childContract, _childTokenId, _amount); } /** * @notice Store data for the received ERC20 * @param _from The current owner address of the ERC20 tokens that are being transferred. * @param _tokenId The token to transfer the ERC20 tokens to. * @param _erc20Contract The ERC20 token contract * @param _value The number of ERC20 tokens to transfer */ function _receiveErc20Child( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) internal virtual override { require(permittedErc20Asset(_erc20Contract), "erc20 not permitted"); super._receiveErc20Child(_from, _tokenId, _erc20Contract, _value); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./ERC998TopDown.sol"; import "../interfaces/IERC998ERC1155TopDown.sol"; /** * @title ERC9981155Extension * @author NFTfi * @dev ERC998TopDown extension to support ERC1155 children */ abstract contract ERC9981155Extension is ERC998TopDown, IERC998ERC1155TopDown, IERC1155Receiver { using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; // tokenId => (child address => (child tokenId => balance)) mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal balances; /** * @dev Gives child balance for a specific child contract and child id * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The tokenId of the child token */ function childBalance( uint256 _tokenId, address _childContract, uint256 _childTokenId ) external view override returns (uint256) { return balances[_tokenId][_childContract][_childTokenId]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC998TopDown, IERC165) returns (bool) { return _interfaceId == type(IERC998ERC1155TopDown).interfaceId || _interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(_interfaceId); } /** * @notice Transfer a ERC1155 child token from top-down composable to address or other top-down composable * @param _tokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred * @param _amount The amount of the token that is being transferred * @param _data Additional data with no specified format */ function safeTransferChild( uint256 _tokenId, address _to, address _childContract, uint256 _childTokenId, uint256 _amount, bytes memory _data ) external override nonReentrant { _validateReceiver(_to); _validate1155ChildTransfer(_tokenId); _remove1155Child(_tokenId, _childContract, _childTokenId, _amount); if (_to == address(this)) { _validateAndReceive1155Child(msg.sender, _childContract, _childTokenId, _amount, _data); } else { IERC1155(_childContract).safeTransferFrom(address(this), _to, _childTokenId, _amount, _data); emit Transfer1155Child(_tokenId, _to, _childContract, _childTokenId, _amount); } } /** * @notice Transfer batch of ERC1155 child token from top-down composable to address or other top-down composable * @param _tokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC1155 contract of the child token * @param _childTokenIds The list of tokenId of the token that is being transferred * @param _amounts The list of amount of the token that is being transferred * @param _data Additional data with no specified format */ function safeBatchTransferChild( uint256 _tokenId, address _to, address _childContract, uint256[] memory _childTokenIds, uint256[] memory _amounts, bytes memory _data ) external override nonReentrant { require(_childTokenIds.length == _amounts.length, "ids and amounts length mismatch"); _validateReceiver(_to); _validate1155ChildTransfer(_tokenId); for (uint256 i = 0; i < _childTokenIds.length; ++i) { uint256 childTokenId = _childTokenIds[i]; uint256 amount = _amounts[i]; _remove1155Child(_tokenId, _childContract, childTokenId, amount); if (_to == address(this)) { _validateAndReceive1155Child(msg.sender, _childContract, childTokenId, amount, _data); } } if (_to != address(this)) { IERC1155(_childContract).safeBatchTransferFrom(address(this), _to, _childTokenIds, _amounts, _data); emit Transfer1155BatchChild(_tokenId, _to, _childContract, _childTokenIds, _amounts); } } /** * @notice A token receives a child token */ function onERC1155Received( address, address, uint256, uint256, bytes memory ) external virtual override returns (bytes4) { revert("external calls restricted"); } /** * @notice A token receives a batch of child tokens * param The address that caused the transfer * @param _from The owner of the child token * @param _ids The list of token id that is being transferred to the parent * @param _values The list of amounts of the tokens that is being transferred * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId * @return the selector of this method */ function onERC1155BatchReceived( address, address _from, uint256[] memory _ids, uint256[] memory _values, bytes memory _data ) external virtual override nonReentrant returns (bytes4) { require(_data.length == 32, "data must contain tokenId to transfer the child token to"); uint256 _receiverTokenId = _parseTokenId(_data); for (uint256 i = 0; i < _ids.length; i++) { _receive1155Child(_receiverTokenId, msg.sender, _ids[i], _values[i]); emit Received1155Child(_from, _receiverTokenId, msg.sender, _ids[i], _values[i]); } return this.onERC1155BatchReceived.selector; } /** * @dev Validates the data of the child token and receives it * @param _from The owner of the child token * @param _childContract The ERC1155 contract of the child token * @param _id The token id that is being transferred to the parent * @param _amount The amount of the token that is being transferred * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId */ function _validateAndReceive1155Child( address _from, address _childContract, uint256 _id, uint256 _amount, bytes memory _data ) internal virtual { require(_data.length == 32, "data must contain tokenId to transfer the child token to"); uint256 _receiverTokenId = _parseTokenId(_data); _receive1155Child(_receiverTokenId, _childContract, _id, _amount); emit Received1155Child(_from, _receiverTokenId, _childContract, _id, _amount); } /** * @dev Updates the state to receive a child * @param _tokenId The token receiving the child * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The token id that is being transferred to the parent * @param _amount The amount of the token that is being transferred */ function _receive1155Child( uint256 _tokenId, address _childContract, uint256 _childTokenId, uint256 _amount ) internal virtual { require(_exists(_tokenId), "bundle tokenId does not exist"); uint256 childTokensLength = childTokens[_tokenId][_childContract].length(); if (childTokensLength == 0) { childContracts[_tokenId].add(_childContract); } childTokens[_tokenId][_childContract].add(_childTokenId); balances[_tokenId][_childContract][_childTokenId] += _amount; } /** * @notice Validates the transfer of a 1155 child * @param _fromTokenId The owning token to transfer from */ function _validate1155ChildTransfer(uint256 _fromTokenId) internal virtual { _validateTransferSender(_fromTokenId); } /** * @notice Updates the state to remove a ERC1155 child * @param _tokenId The owning token to transfer from * @param _childContract The ERC1155 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred * @param _amount The amount of the token that is being transferred */ function _remove1155Child( uint256 _tokenId, address _childContract, uint256 _childTokenId, uint256 _amount ) internal virtual { require( _amount != 0 && balances[_tokenId][_childContract][_childTokenId] >= _amount, "insufficient child balance for transfer" ); balances[_tokenId][_childContract][_childTokenId] -= _amount; if (balances[_tokenId][_childContract][_childTokenId] == 0) { // remove child token childTokens[_tokenId][_childContract].remove(_childTokenId); // remove contract if (childTokens[_tokenId][_childContract].length() == 0) { childContracts[_tokenId].remove(_childContract); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./ERC998TopDown.sol"; import "../interfaces/IERC998ERC20TopDown.sol"; import "../interfaces/IERC998ERC20TopDownEnumerable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; /** * @title ERC998ERC20Extension * @author NFTfi * @dev ERC998TopDown extension to support ERC20 children */ abstract contract ERC998ERC20Extension is ERC998TopDown, IERC998ERC20TopDown, IERC998ERC20TopDownEnumerable { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; // tokenId => ERC20 child contract mapping(uint256 => EnumerableSet.AddressSet) internal erc20ChildContracts; // tokenId => (token contract => balance) mapping(uint256 => mapping(address => uint256)) internal erc20Balances; /** * @dev Look up the balance of ERC20 tokens for a specific token and ERC20 contract * @param _tokenId The token that owns the ERC20 tokens * @param _erc20Contract The ERC20 contract * @return The number of ERC20 tokens owned by a token */ function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view virtual override returns (uint256) { return erc20Balances[_tokenId][_erc20Contract]; } /** * @notice Get ERC20 contract by tokenId and index * @param _tokenId The parent token of ERC20 tokens * @param _index The index position of the child contract * @return childContract The contract found at the tokenId and index */ function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view virtual override returns (address) { return erc20ChildContracts[_tokenId].at(_index); } /** * @notice Get the total number of ERC20 tokens owned by tokenId * @param _tokenId The parent token of ERC20 tokens * @return uint256 The total number of ERC20 tokens */ function totalERC20Contracts(uint256 _tokenId) external view virtual override returns (uint256) { return erc20ChildContracts[_tokenId].length(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC998TopDown) returns (bool) { return _interfaceId == type(IERC998ERC20TopDown).interfaceId || _interfaceId == type(IERC998ERC20TopDownEnumerable).interfaceId || super.supportsInterface(_interfaceId); } /** * @notice Transfer ERC20 tokens to address * @param _tokenId The token to transfer from * @param _to The address to send the ERC20 tokens to * @param _erc20Contract The ERC20 contract * @param _value The number of ERC20 tokens to transfer */ function transferERC20( uint256 _tokenId, address _to, address _erc20Contract, uint256 _value ) external virtual override { _validateERC20Value(_value); _validateReceiver(_to); _validateERC20Transfer(_tokenId); _removeERC20(_tokenId, _erc20Contract, _value); IERC20(_erc20Contract).safeTransfer(_to, _value); emit TransferERC20(_tokenId, _to, _erc20Contract, _value); } /** * @notice Get ERC20 tokens from ERC20 contract. * @dev This contract has to be approved first by _erc20Contract */ function getERC20( address, uint256, address, uint256 ) external pure override { revert("external calls restricted"); } /** * @notice NOT SUPPORTED * Intended to transfer ERC223 tokens. ERC223 tokens can be transferred as regular ERC20 */ function transferERC223( uint256, address, address, uint256, bytes calldata ) external virtual override { revert("TRANSFER_ERC223_NOT_SUPPORTED"); } /** * @notice NOT SUPPORTED * Intended to receive ERC223 tokens. ERC223 tokens can be deposited as regular ERC20 */ function tokenFallback( address, uint256, bytes calldata ) external virtual override { revert("TOKEN_FALLBACK_ERC223_NOT_SUPPORTED"); } /** * @notice Get ERC20 tokens from ERC20 contract. * @dev This contract has to be approved first by _erc20Contract * @param _from The current owner address of the ERC20 tokens that are being transferred. * @param _tokenId The token to transfer the ERC20 tokens to. * @param _erc20Contract The ERC20 token contract * @param _value The number of ERC20 tokens to transfer */ function _getERC20( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) internal { _validateERC20Value(_value); _receiveErc20Child(_from, _tokenId, _erc20Contract, _value); IERC20(_erc20Contract).safeTransferFrom(_from, address(this), _value); } /** * @notice Validates the value of a ERC20 transfer * @param _value The number of ERC20 tokens to transfer */ function _validateERC20Value(uint256 _value) internal virtual { require(_value > 0, "zero amount"); } /** * @notice Validates the transfer of a ERC20 * @param _fromTokenId The owning token to transfer from */ function _validateERC20Transfer(uint256 _fromTokenId) internal virtual { _validateTransferSender(_fromTokenId); } /** * @notice Store data for the received ERC20 * @param _from The current owner address of the ERC20 tokens that are being transferred. * @param _tokenId The token to transfer the ERC20 tokens to. * @param _erc20Contract The ERC20 token contract * @param _value The number of ERC20 tokens to transfer */ function _receiveErc20Child( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) internal virtual { require(_exists(_tokenId), "bundle tokenId does not exist"); uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract]; if (erc20Balance == 0) { erc20ChildContracts[_tokenId].add(_erc20Contract); } erc20Balances[_tokenId][_erc20Contract] += _value; emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value); } /** * @notice Updates the state to remove ERC20 tokens * @param _tokenId The token to transfer from * @param _erc20Contract The ERC20 contract * @param _value The number of ERC20 tokens to transfer */ function _removeERC20( uint256 _tokenId, address _erc20Contract, uint256 _value ) internal virtual { uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract]; require(erc20Balance >= _value, "not enough token available to transfer"); uint256 newERC20Balance = erc20Balance - _value; erc20Balances[_tokenId][_erc20Contract] = newERC20Balance; if (newERC20Balance == 0) { erc20ChildContracts[_tokenId].remove(_erc20Contract); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title ContractKeys * @author NFTfi * @dev Common library for contract keys */ library ContractKeys { bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S"); bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS"); bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS"); bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY"); bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY"); bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER"); bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S"); bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS"); bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER"); bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY"); bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN"); bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER"); string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper"; /** * @notice Returns the bytes32 representation of a string * @param _key the string key * @return id bytes32 representation */ function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) { require(bytes(_key).length <= 32, "invalid key"); // solhint-disable-next-line no-inline-assembly assembly { id := mload(add(_key, 32)) } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IBundleBuilder { /** * @notice data of a erc721 bundle element * * @param tokenContract - address of the token contract * @param id - id of the token * @param safeTransferable - wether the implementing token contract has a safeTransfer function or not */ struct BundleElementERC721 { address tokenContract; uint256 id; bool safeTransferable; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param amount - amount of the token */ struct BundleElementERC20 { address tokenContract; uint256 amount; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param ids - list of ids of the tokens * @param amounts - list amounts of the tokens */ struct BundleElementERC1155 { address tokenContract; uint256[] ids; uint256[] amounts; } /** * @notice the lists of erc721-20-1155 tokens that are to be bundled * * @param erc721s list of erc721 tokens * @param erc20s list of erc20 tokens * @param erc1155s list of erc1155 tokens */ struct BundleElements { BundleElementERC721[] erc721s; BundleElementERC20[] erc20s; BundleElementERC1155[] erc1155s; } /** * @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan, * returns the id of the created bundle * * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _sender sender of the tokens in the bundle - the borrower * @param _receiver receiver of the created bundle, normally the loan contract */ function buildBundle( BundleElements memory _bundleElements, address _sender, address _receiver ) external returns (uint256); /** * @notice Remove all the children from the bundle * @dev This method may run out of gas if the list of children is too big. In that case, children can be removed * individually. * @param _tokenId the id of the bundle * @param _receiver address of the receiver of the children */ function decomposeBundle(uint256 _tokenId, address _receiver) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./IERC998ERC721TopDown.sol"; interface INftfiBundler is IERC721 { function safeMint(address _to) external returns (uint256); function decomposeBundle(uint256 _tokenId, address _receiver) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftfiHub * @author NFTfi * @dev NftfiHub interface */ interface INftfiHub { function setContract(string calldata _contractKey, address _contractAddress) external; function getContract(bytes32 _contractKey) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedNFTs { function setNFTPermit(address _nftContract, string memory _nftType) external; function getNFTPermit(address _nftContract) external view returns (bytes32); function getNFTWrapper(address _nftContract) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedERC20s { function getERC20Permit(address _erc20) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @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); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../interfaces/IERC998ERC721TopDown.sol"; import "../interfaces/IERC998ERC721TopDownEnumerable.sol"; /** * @title ERC998TopDown * @author NFTfi * @dev ERC998ERC721 Top-Down Composable Non-Fungible Token. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md * This implementation does not support children to be nested bundles, erc20 nor bottom-up */ abstract contract ERC998TopDown is ERC721Enumerable, IERC998ERC721TopDown, IERC998ERC721TopDownEnumerable, ReentrancyGuard { using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; // return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^ // this.tokenOwnerOf.selector ^ this.ownerOfChild.selector; bytes32 public constant ERC998_MAGIC_VALUE = 0xcd740db500000000000000000000000000000000000000000000000000000000; bytes32 internal constant ERC998_MAGIC_MASK = 0xffffffff00000000000000000000000000000000000000000000000000000000; uint256 public tokenCount = 0; // tokenId => child contract mapping(uint256 => EnumerableSet.AddressSet) internal childContracts; // tokenId => (child address => array of child tokens) mapping(uint256 => mapping(address => EnumerableSet.UintSet)) internal childTokens; // child address => childId => tokenId // this is used for ERC721 type tokens mapping(address => mapping(uint256 => uint256)) internal childTokenOwner; /** * @notice Tells whether the ERC721 type child exists or not * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child * @return True if the child exists, false otherwise */ function childExists(address _childContract, uint256 _childTokenId) external view virtual returns (bool) { uint256 tokenId = childTokenOwner[_childContract][_childTokenId]; return tokenId != 0; } /** * @notice Get the total number of child contracts with tokens that are owned by _tokenId * @param _tokenId The parent token of child tokens in child contracts * @return uint256 The total number of child contracts with tokens owned by _tokenId */ function totalChildContracts(uint256 _tokenId) external view virtual override returns (uint256) { return childContracts[_tokenId].length(); } /** * @notice Get child contract by tokenId and index * @param _tokenId The parent token of child tokens in child contract * @param _index The index position of the child contract * @return childContract The contract found at the _tokenId and index */ function childContractByIndex(uint256 _tokenId, uint256 _index) external view virtual override returns (address childContract) { return childContracts[_tokenId].at(_index); } /** * @notice Get the total number of child tokens owned by tokenId that exist in a child contract * @param _tokenId The parent token of child tokens * @param _childContract The child contract containing the child tokens * @return uint256 The total number of child tokens found in child contract that are owned by _tokenId */ function totalChildTokens(uint256 _tokenId, address _childContract) external view override returns (uint256) { return childTokens[_tokenId][_childContract].length(); } /** * @notice Get child token owned by _tokenId, in child contract, at index position * @param _tokenId The parent token of the child token * @param _childContract The child contract of the child token * @param _index The index position of the child token * @return childTokenId The child tokenId for the parent token, child token and index */ function childTokenByIndex( uint256 _tokenId, address _childContract, uint256 _index ) external view virtual override returns (uint256 childTokenId) { return childTokens[_tokenId][_childContract].at(_index); } /** * @notice Get the parent tokenId and its owner of a ERC721 child token * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child * @return parentTokenOwner The parent address of the parent token and ERC998 magic value * @return parentTokenId The parent tokenId of _childTokenId */ function ownerOfChild(address _childContract, uint256 _childTokenId) external view virtual override returns (bytes32 parentTokenOwner, uint256 parentTokenId) { parentTokenId = childTokenOwner[_childContract][_childTokenId]; require(parentTokenId != 0, "owner of child not found"); address parentTokenOwnerAddress = ownerOf(parentTokenId); // solhint-disable-next-line no-inline-assembly assembly { parentTokenOwner := or(ERC998_MAGIC_VALUE, parentTokenOwnerAddress) } } /** * @notice Get the root owner of tokenId * @param _tokenId The token to query for a root owner address * @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value. */ function rootOwnerOf(uint256 _tokenId) public view virtual override returns (bytes32 rootOwner) { return rootOwnerOfChild(address(0), _tokenId); } /** * @notice Get the root owner of a child token * @dev Returns the owner at the top of the tree of composables * Use Cases handled: * - Case 1: Token owner is this contract and token. * - Case 2: Token owner is other external top-down composable * - Case 3: Token owner is other contract * - Case 4: Token owner is user * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child * @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value */ function rootOwnerOfChild(address _childContract, uint256 _childTokenId) public view virtual override returns (bytes32 rootOwner) { address rootOwnerAddress; if (_childContract != address(0)) { (rootOwnerAddress, _childTokenId) = _ownerOfChild(_childContract, _childTokenId); } else { rootOwnerAddress = ownerOf(_childTokenId); } if (rootOwnerAddress.isContract()) { try IERC998ERC721TopDown(rootOwnerAddress).rootOwnerOfChild(address(this), _childTokenId) returns ( bytes32 returnedRootOwner ) { // Case 2: Token owner is other external top-down composable if (returnedRootOwner & ERC998_MAGIC_MASK == ERC998_MAGIC_VALUE) { return returnedRootOwner; } } catch { // solhint-disable-previous-line no-empty-blocks } } // Case 3: Token owner is other contract // Or // Case 4: Token owner is user // solhint-disable-next-line no-inline-assembly assembly { rootOwner := or(ERC998_MAGIC_VALUE, rootOwnerAddress) } return rootOwner; } /** * @dev See {IERC165-supportsInterface}. * The interface id 0x1efdf36a is added. The spec claims it to be the interface id of IERC998ERC721TopDown. * But it is not. * It is added anyway in case some contract checks it being compliant with the spec. */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC721Enumerable) returns (bool) { return _interfaceId == type(IERC998ERC721TopDown).interfaceId || _interfaceId == type(IERC998ERC721TopDownEnumerable).interfaceId || _interfaceId == 0x1efdf36a || super.supportsInterface(_interfaceId); } /** * @notice Mints a new bundle * @param _to The address that owns the new bundle * @return The id of the new bundle */ function _safeMint(address _to) internal returns (uint256) { uint256 id = ++tokenCount; _safeMint(_to, id); return id; } /** * @notice Transfer child token from top-down composable to address * @param _fromTokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external virtual override nonReentrant { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); IERC721(_childContract).safeTransferFrom(address(this), _to, _childTokenId); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } /** * @notice Transfer child token from top-down composable to address or other top-down composable * @param _fromTokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred * @param _data Additional data with no specified format */ function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes memory _data ) external virtual override nonReentrant { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); if (_to == address(this)) { _validateAndReceiveChild(msg.sender, _childContract, _childTokenId, _data); } else { IERC721(_childContract).safeTransferFrom(address(this), _to, _childTokenId, _data); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } } /** * @dev Transfer child token from top-down composable to address * @param _fromTokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external virtual override nonReentrant { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); _oldNFTsTransfer(_to, _childContract, _childTokenId); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } /** * @notice NOT SUPPORTED * Intended to transfer bottom-up composable child token from top-down composable to other ERC721 token. */ function transferChildToParent( uint256, address, uint256, address, uint256, bytes memory ) external pure override { revert("BOTTOM_UP_CHILD_NOT_SUPPORTED"); } /** * @notice Transfer a child token from an ERC721 contract to a composable. Used for old tokens that does not * have a safeTransferFrom method like cryptokitties */ function getChild( address, uint256, address, uint256 ) external pure override { revert("external calls restricted"); } /** * @notice Transfer a child token from an ERC721 contract to a composable. Used for old tokens that does not * have a safeTransferFrom method like cryptokitties * @dev This contract has to be approved first in _childContract * @param _from The address that owns the child token. * @param _tokenId The token that becomes the parent owner * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the child token */ function _getChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) internal virtual nonReentrant { _receiveChild(_from, _tokenId, _childContract, _childTokenId); IERC721(_childContract).transferFrom(_from, address(this), _childTokenId); } /** * @notice A token receives a child token * param The address that caused the transfer * @param _from The owner of the child token * @param _childTokenId The token that is being transferred to the parent * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId * @return the selector of this method */ function onERC721Received( address, address _from, uint256 _childTokenId, bytes calldata _data ) external virtual override nonReentrant returns (bytes4) { _validateAndReceiveChild(_from, msg.sender, _childTokenId, _data); return this.onERC721Received.selector; } /** * @dev ERC721 implementation hook that is called before any token transfer. Prevents nested bundles * @param _from address of the current owner of the token * @param _to destination address * @param _tokenId id of the token to transfer */ function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal virtual override { require(_to != address(this), "nested bundles not allowed"); super._beforeTokenTransfer(_from, _to, _tokenId); } /** * @dev Validates the child transfer parameters and remove the child from the bundle * @param _fromTokenId The owning token to transfer from * @param _to The address that receives the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function _transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) internal virtual { _validateReceiver(_to); _validateChildTransfer(_fromTokenId, _childContract, _childTokenId); _removeChild(_fromTokenId, _childContract, _childTokenId); } /** * @dev Validates the child transfer parameters * @param _fromTokenId The owning token to transfer from * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function _validateChildTransfer( uint256 _fromTokenId, address _childContract, uint256 _childTokenId ) internal virtual { uint256 tokenId = childTokenOwner[_childContract][_childTokenId]; require(tokenId != 0, "_transferChild _childContract _childTokenId not found"); require(tokenId == _fromTokenId, "ComposableTopDown: _transferChild wrong tokenId found"); _validateTransferSender(tokenId); } /** * @dev Validates the receiver of a child transfer * @param _to The address that receives the child token */ function _validateReceiver(address _to) internal virtual { require(_to != address(0), "child transfer to zero address"); } /** * @dev Updates the state to remove a child * @param _tokenId The owning token to transfer from * @param _childContract The ERC721 contract of the child token * @param _childTokenId The tokenId of the token that is being transferred */ function _removeChild( uint256 _tokenId, address _childContract, uint256 _childTokenId ) internal virtual { // remove child token childTokens[_tokenId][_childContract].remove(_childTokenId); delete childTokenOwner[_childContract][_childTokenId]; // remove contract if (childTokens[_tokenId][_childContract].length() == 0) { childContracts[_tokenId].remove(_childContract); } } /** * @dev Validates the data from a child transfer and receives it * @param _from The owner of the child token * @param _childContract The ERC721 contract of the child token * @param _childTokenId The token that is being transferred to the parent * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId */ function _validateAndReceiveChild( address _from, address _childContract, uint256 _childTokenId, bytes memory _data ) internal virtual { require(_data.length > 0, "data must contain tokenId to transfer the child token to"); // convert up to 32 bytes of _data to uint256, owner nft tokenId passed as uint in bytes uint256 tokenId = _parseTokenId(_data); _receiveChild(_from, tokenId, _childContract, _childTokenId); } /** * @dev Update the state to receive a child * @param _from The owner of the child token * @param _tokenId The token receiving the child * @param _childContract The ERC721 contract of the child token * @param _childTokenId The token that is being transferred to the parent */ function _receiveChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) internal virtual { require(_exists(_tokenId), "bundle tokenId does not exist"); uint256 childTokensLength = childTokens[_tokenId][_childContract].length(); if (childTokensLength == 0) { childContracts[_tokenId].add(_childContract); } childTokens[_tokenId][_childContract].add(_childTokenId); childTokenOwner[_childContract][_childTokenId] = _tokenId; emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId); } /** * @dev Returns the owner of a child * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child * @return parentTokenOwner The parent address of the parent token and ERC998 magic value * @return parentTokenId The parent tokenId of _childTokenId */ function _ownerOfChild(address _childContract, uint256 _childTokenId) internal view virtual returns (address parentTokenOwner, uint256 parentTokenId) { parentTokenId = childTokenOwner[_childContract][_childTokenId]; require(parentTokenId != 0, "owner of child not found"); return (ownerOf(parentTokenId), parentTokenId); } /** * @dev Convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes * @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId * @return tokenId the token Id encoded in the data */ function _parseTokenId(bytes memory _data) internal pure virtual returns (uint256 tokenId) { // solhint-disable-next-line no-inline-assembly assembly { tokenId := mload(add(_data, 0x20)) } } /** * @dev Transfers the NFT using method compatible with old token contracts * @param _to address of the receiver of the children * @param _childContract The contract address of the child token * @param _childTokenId The tokenId of the child */ function _oldNFTsTransfer( address _to, address _childContract, uint256 _childTokenId ) internal { // This is here to be compatible with cryptokitties and other old contracts that require being owner and // approved before transferring. // Does not work with current standard which does not allow approving self, so we must let it fail in that case. try IERC721(_childContract).approve(address(this), _childTokenId) { // solhint-disable-previous-line no-empty-blocks } catch { // solhint-disable-previous-line no-empty-blocks } IERC721(_childContract).transferFrom(address(this), _to, _childTokenId); } /** * @notice Validates that the sender is authorized to perform a child transfer * @param _fromTokenId The owning token to transfer from */ function _validateTransferSender(uint256 _fromTokenId) internal virtual { address rootOwner = address(uint160(uint256(rootOwnerOf(_fromTokenId)))); require( rootOwner == msg.sender || getApproved(_fromTokenId) == msg.sender || isApprovedForAll(rootOwner, msg.sender), "transferChild msg.sender not eligible" ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC1155TopDown { event Received1155Child( address indexed from, uint256 indexed toTokenId, address indexed childContract, uint256 childTokenId, uint256 amount ); event Transfer1155Child( uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256 childTokenId, uint256 amount ); event Transfer1155BatchChild( uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256[] childTokenIds, uint256[] amounts ); function safeTransferChild( uint256 fromTokenId, address to, address childContract, uint256 childTokenId, uint256 amount, bytes calldata data ) external; function safeBatchTransferChild( uint256 fromTokenId, address to, address childContract, uint256[] calldata childTokenIds, uint256[] calldata amounts, bytes calldata data ) external; function childBalance( uint256 tokenId, address childContract, uint256 childTokenId ) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC721TopDown { event ReceivedChild( address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId ); event TransferChild( uint256 indexed tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId ); function onERC721Received( address _operator, address _from, uint256 _childTokenId, bytes calldata _data ) external returns (bytes4); function transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external; function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external; function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes memory _data ) external; function transferChildToParent( uint256 _fromTokenId, address _toContract, uint256 _toTokenId, address _childContract, uint256 _childTokenId, bytes memory _data ) external; // getChild function enables older contracts like cryptokitties to be transferred into a composable // The _childContract must approve this contract. Then getChild can be called. function getChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) external; function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner); function rootOwnerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 rootOwner); function ownerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 parentTokenOwner, uint256 parentTokenId); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC721TopDownEnumerable { function totalChildContracts(uint256 _tokenId) external view returns (uint256); function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract); function totalChildTokens(uint256 _tokenId, address _childContract) external view returns (uint256); function childTokenByIndex( uint256 _tokenId, address _childContract, uint256 _index ) external view returns (uint256 childTokenId); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @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 v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC20TopDown { event ReceivedERC20( address indexed _from, uint256 indexed _tokenId, address indexed _erc20Contract, uint256 _value ); event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value); function balanceOfERC20(uint256 _tokenId, address __erc20Contract) external view returns (uint256); function tokenFallback( address _from, uint256 _value, bytes calldata _data ) external; function transferERC20( uint256 _tokenId, address _to, address _erc20Contract, uint256 _value ) external; function transferERC223( uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes calldata _data ) external; function getERC20( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IERC998ERC20TopDownEnumerable { function totalERC20Contracts(uint256 _tokenId) external view returns (uint256); function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) 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); }
* @notice Get the total number of ERC20 tokens owned by tokenId @param _tokenId The parent token of ERC20 tokens @return uint256 The total number of ERC20 tokens/
function totalERC20Contracts(uint256 _tokenId) external view virtual override returns (uint256) { return erc20ChildContracts[_tokenId].length(); }
1,483,175
[ 1, 967, 326, 2078, 1300, 434, 4232, 39, 3462, 2430, 16199, 635, 1147, 548, 225, 389, 2316, 548, 1021, 982, 1147, 434, 4232, 39, 3462, 2430, 327, 2254, 5034, 1021, 2078, 1300, 434, 4232, 39, 3462, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 654, 39, 3462, 20723, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 6445, 71, 3462, 1763, 20723, 63, 67, 2316, 548, 8009, 2469, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; import './levels/base/Level.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; contract Ethernaut is Ownable { // ---------------------------------- // Owner interaction // ---------------------------------- mapping(address => bool) registeredLevels; // Only registered levels will be allowed to generate and validate level instances. function registerLevel(Level _level) public onlyOwner { registeredLevels[address(_level)] = true; } // ---------------------------------- // Get/submit level instances // ---------------------------------- struct EmittedInstanceData { address player; Level level; bool completed; } mapping(address => EmittedInstanceData) emittedInstances; event LevelInstanceCreatedLog(address indexed player, address instance); event LevelCompletedLog(address indexed player, Level level); function createLevelInstance(Level _level) public payable { // Ensure level is registered. require(registeredLevels[address(_level)]); // Get level factory to create an instance. address instance = _level.createInstance.value(msg.value)(msg.sender); // Store emitted instance relationship with player and level. emittedInstances[instance] = EmittedInstanceData(msg.sender, _level, false); // Retrieve created instance via logs. emit LevelInstanceCreatedLog(msg.sender, instance); } function submitLevelInstance(address payable _instance) public { // Get player and level. EmittedInstanceData storage data = emittedInstances[_instance]; require(data.player == msg.sender); // instance was emitted for this player require(data.completed == false); // not already submitted // Have the level check the instance. if(data.level.validateInstance(_instance, msg.sender)) { // Register instance as completed. data.completed = true; // Notify success via logs. emit LevelCompletedLog(msg.sender, data.level); } } }
Get player and level. Have the level check the instance. Register instance as completed. Notify success via logs.
function submitLevelInstance(address payable _instance) public { EmittedInstanceData storage data = emittedInstances[_instance]; if(data.level.validateInstance(_instance, msg.sender)) { data.completed = true; emit LevelCompletedLog(msg.sender, data.level); } }
6,463,124
[ 1, 967, 7291, 471, 1801, 18, 21940, 326, 1801, 866, 326, 791, 18, 5433, 791, 487, 5951, 18, 10918, 2216, 3970, 5963, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4879, 2355, 1442, 12, 2867, 8843, 429, 389, 1336, 13, 1071, 288, 203, 203, 565, 512, 7948, 1442, 751, 2502, 501, 273, 17826, 5361, 63, 67, 1336, 15533, 203, 203, 565, 309, 12, 892, 18, 2815, 18, 5662, 1442, 24899, 1336, 16, 1234, 18, 15330, 3719, 288, 203, 203, 1377, 501, 18, 13615, 273, 638, 31, 203, 203, 1377, 3626, 4557, 9556, 1343, 12, 3576, 18, 15330, 16, 501, 18, 2815, 1769, 203, 565, 289, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; import "../ERC20Interface.sol"; import "../ConversionRates.sol"; import "./WrapperBase.sol"; contract WrapConversionRate is WrapperBase { ConversionRates internal conversionRates; //add token parameters struct AddTokenData { ERC20 token; uint minimalResolution; // can be roughly 1 cent uint maxPerBlockImbalance; // in twei resolution uint maxTotalImbalance; } AddTokenData internal addTokenData; //set token control info parameters. struct TokenControlInfoData { ERC20[] tokens; uint[] perBlockImbalance; // in twei resolution uint[] maxTotalImbalance; } TokenControlInfoData internal tokenControlInfoData; //valid duration struct ValidDurationData { uint durationInBlocks; } ValidDurationData internal validDurationData; //data indexes uint constant internal ADD_TOKEN_DATA_INDEX = 0; uint constant internal TOKEN_INFO_DATA_INDEX = 1; uint constant internal VALID_DURATION_DATA_INDEX = 2; uint constant internal NUM_DATA_INDEX = 3; //general functions function WrapConversionRate(ConversionRates _conversionRates, address _admin) public WrapperBase(PermissionGroups(address(_conversionRates)), _admin, NUM_DATA_INDEX) { require(_conversionRates != address(0)); conversionRates = _conversionRates; } // add token functions ////////////////////// function setAddTokenData( ERC20 token, uint minRecordResolution, uint maxPerBlockImbalance, uint maxTotalImbalance ) public onlyOperator { require(token != address(0)); require(minRecordResolution != 0); require(maxPerBlockImbalance != 0); require(maxTotalImbalance != 0); //update data tracking setNewData(ADD_TOKEN_DATA_INDEX); addTokenData.token = token; addTokenData.minimalResolution = minRecordResolution; // can be roughly 1 cent addTokenData.maxPerBlockImbalance = maxPerBlockImbalance; // in twei resolution addTokenData.maxTotalImbalance = maxTotalImbalance; } function approveAddTokenData(uint nonce) public onlyOperator { if (addSignature(ADD_TOKEN_DATA_INDEX, nonce, msg.sender)) { // can perform operation. performAddToken(); } } function getAddTokenData() public view returns(uint nonce, ERC20 token, uint minRecordResolution, uint maxPerBlockImbalance, uint maxTotalImbalance) { address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(ADD_TOKEN_DATA_INDEX); token = addTokenData.token; minRecordResolution = addTokenData.minimalResolution; maxPerBlockImbalance = addTokenData.maxPerBlockImbalance; // in twei resolution maxTotalImbalance = addTokenData.maxTotalImbalance; return(nonce, token, minRecordResolution, maxPerBlockImbalance, maxTotalImbalance); } function getAddTokenSignatures() public view returns (address[] memory signatures) { uint nonce; (signatures, nonce) = getDataTrackingParameters(ADD_TOKEN_DATA_INDEX); return(signatures); } //set token control info //////////////////////// function setTokenInfoData(ERC20[] tokens, uint[] maxPerBlockImbalanceValues, uint[] maxTotalImbalanceValues) public onlyOperator { require(maxPerBlockImbalanceValues.length == tokens.length); require(maxTotalImbalanceValues.length == tokens.length); //update data tracking setNewData(TOKEN_INFO_DATA_INDEX); tokenControlInfoData.tokens = tokens; tokenControlInfoData.perBlockImbalance = maxPerBlockImbalanceValues; tokenControlInfoData.maxTotalImbalance = maxTotalImbalanceValues; } function approveTokenControlInfo(uint nonce) public onlyOperator { if (addSignature(TOKEN_INFO_DATA_INDEX, nonce, msg.sender)) { // can perform operation. performSetTokenControlInfo(); } } function getControlInfoPerToken (uint index) public view returns(ERC20 token, uint _maxPerBlockImbalance, uint _maxTotalImbalance, uint nonce) { require(tokenControlInfoData.tokens.length > index); require(tokenControlInfoData.perBlockImbalance.length > index); require(tokenControlInfoData.maxTotalImbalance.length > index); address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(TOKEN_INFO_DATA_INDEX); return( tokenControlInfoData.tokens[index], tokenControlInfoData.perBlockImbalance[index], tokenControlInfoData.maxTotalImbalance[index], nonce ); } function getTokenInfoNumToknes() public view returns(uint numSetTokens) { return tokenControlInfoData.tokens.length; } function getTokenInfoData() public view returns(uint nonce, uint numSetTokens, ERC20[] tokenAddress, uint[] maxPerBlock, uint[] maxTotal) { address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(TOKEN_INFO_DATA_INDEX); return( nonce, tokenControlInfoData.tokens.length, tokenControlInfoData.tokens, tokenControlInfoData.perBlockImbalance, tokenControlInfoData.maxTotalImbalance); } function getTokenInfoSignatures() public view returns (address[] memory signatures) { uint nonce; (signatures, nonce) = getDataTrackingParameters(TOKEN_INFO_DATA_INDEX); return(signatures); } function getTokenInfoNonce() public view returns(uint nonce) { address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(TOKEN_INFO_DATA_INDEX); return nonce; } //valid duration blocks /////////////////////// function setValidDurationData(uint validDurationBlocks) public onlyOperator { require(validDurationBlocks > 5); //update data tracking setNewData(VALID_DURATION_DATA_INDEX); validDurationData.durationInBlocks = validDurationBlocks; } function approveValidDurationData(uint nonce) public onlyOperator { if (addSignature(VALID_DURATION_DATA_INDEX, nonce, msg.sender)) { // can perform operation. conversionRates.setValidRateDurationInBlocks(validDurationData.durationInBlocks); } } function getValidDurationBlocksData() public view returns(uint validDuration, uint nonce) { address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(VALID_DURATION_DATA_INDEX); return(nonce, validDurationData.durationInBlocks); } function getValidDurationSignatures() public view returns (address[] memory signatures) { uint nonce; (signatures, nonce) = getDataTrackingParameters(VALID_DURATION_DATA_INDEX); return(signatures); } function performAddToken() internal { conversionRates.addToken(addTokenData.token); conversionRates.addOperator(this); //token control info conversionRates.setTokenControlInfo( addTokenData.token, addTokenData.minimalResolution, addTokenData.maxPerBlockImbalance, addTokenData.maxTotalImbalance ); //step functions int[] memory zeroArr = new int[](1); zeroArr[0] = 0; conversionRates.setQtyStepFunction(addTokenData.token, zeroArr, zeroArr, zeroArr, zeroArr); conversionRates.setImbalanceStepFunction(addTokenData.token, zeroArr, zeroArr, zeroArr, zeroArr); conversionRates.enableTokenTrade(addTokenData.token); conversionRates.removeOperator(this); } function performSetTokenControlInfo() internal { require(tokenControlInfoData.tokens.length == tokenControlInfoData.perBlockImbalance.length); require(tokenControlInfoData.tokens.length == tokenControlInfoData.maxTotalImbalance.length); uint minRecordResolution; for (uint i = 0; i < tokenControlInfoData.tokens.length; i++) { uint maxPerBlock; uint maxTotal; (minRecordResolution, maxPerBlock, maxTotal) = conversionRates.getTokenControlInfo(tokenControlInfoData.tokens[i]); require(minRecordResolution != 0); conversionRates.setTokenControlInfo(tokenControlInfoData.tokens[i], minRecordResolution, tokenControlInfoData.perBlockImbalance[i], tokenControlInfoData.maxTotalImbalance[i]); } } }
add token parameters
contract WrapConversionRate is WrapperBase { ConversionRates internal conversionRates; struct AddTokenData { ERC20 token; uint maxTotalImbalance; } AddTokenData internal addTokenData; struct TokenControlInfoData { ERC20[] tokens; uint[] maxTotalImbalance; } TokenControlInfoData internal tokenControlInfoData; struct ValidDurationData { uint durationInBlocks; } ValidDurationData internal validDurationData; uint constant internal TOKEN_INFO_DATA_INDEX = 1; uint constant internal VALID_DURATION_DATA_INDEX = 2; uint constant internal NUM_DATA_INDEX = 3; uint constant internal ADD_TOKEN_DATA_INDEX = 0; function WrapConversionRate(ConversionRates _conversionRates, address _admin) public WrapperBase(PermissionGroups(address(_conversionRates)), _admin, NUM_DATA_INDEX) { require(_conversionRates != address(0)); conversionRates = _conversionRates; } function setAddTokenData( ERC20 token, uint minRecordResolution, uint maxPerBlockImbalance, uint maxTotalImbalance ) public onlyOperator { require(token != address(0)); require(minRecordResolution != 0); require(maxPerBlockImbalance != 0); require(maxTotalImbalance != 0); setNewData(ADD_TOKEN_DATA_INDEX); addTokenData.token = token; addTokenData.maxTotalImbalance = maxTotalImbalance; } function approveAddTokenData(uint nonce) public onlyOperator { if (addSignature(ADD_TOKEN_DATA_INDEX, nonce, msg.sender)) { performAddToken(); } } function approveAddTokenData(uint nonce) public onlyOperator { if (addSignature(ADD_TOKEN_DATA_INDEX, nonce, msg.sender)) { performAddToken(); } } function getAddTokenData() public view returns(uint nonce, ERC20 token, uint minRecordResolution, uint maxPerBlockImbalance, uint maxTotalImbalance) { address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(ADD_TOKEN_DATA_INDEX); token = addTokenData.token; minRecordResolution = addTokenData.minimalResolution; maxTotalImbalance = addTokenData.maxTotalImbalance; return(nonce, token, minRecordResolution, maxPerBlockImbalance, maxTotalImbalance); } function getAddTokenSignatures() public view returns (address[] memory signatures) { uint nonce; (signatures, nonce) = getDataTrackingParameters(ADD_TOKEN_DATA_INDEX); return(signatures); } function setTokenInfoData(ERC20[] tokens, uint[] maxPerBlockImbalanceValues, uint[] maxTotalImbalanceValues) public onlyOperator { require(maxPerBlockImbalanceValues.length == tokens.length); require(maxTotalImbalanceValues.length == tokens.length); setNewData(TOKEN_INFO_DATA_INDEX); tokenControlInfoData.tokens = tokens; tokenControlInfoData.perBlockImbalance = maxPerBlockImbalanceValues; tokenControlInfoData.maxTotalImbalance = maxTotalImbalanceValues; } function approveTokenControlInfo(uint nonce) public onlyOperator { if (addSignature(TOKEN_INFO_DATA_INDEX, nonce, msg.sender)) { performSetTokenControlInfo(); } } function approveTokenControlInfo(uint nonce) public onlyOperator { if (addSignature(TOKEN_INFO_DATA_INDEX, nonce, msg.sender)) { performSetTokenControlInfo(); } } function getControlInfoPerToken (uint index) public view returns(ERC20 token, uint _maxPerBlockImbalance, uint _maxTotalImbalance, uint nonce) { require(tokenControlInfoData.tokens.length > index); require(tokenControlInfoData.perBlockImbalance.length > index); require(tokenControlInfoData.maxTotalImbalance.length > index); address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(TOKEN_INFO_DATA_INDEX); return( tokenControlInfoData.tokens[index], tokenControlInfoData.perBlockImbalance[index], tokenControlInfoData.maxTotalImbalance[index], nonce ); } function getTokenInfoNumToknes() public view returns(uint numSetTokens) { return tokenControlInfoData.tokens.length; } function getTokenInfoData() public view returns(uint nonce, uint numSetTokens, ERC20[] tokenAddress, uint[] maxPerBlock, uint[] maxTotal) { address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(TOKEN_INFO_DATA_INDEX); return( nonce, tokenControlInfoData.tokens.length, tokenControlInfoData.tokens, tokenControlInfoData.perBlockImbalance, tokenControlInfoData.maxTotalImbalance); } function getTokenInfoSignatures() public view returns (address[] memory signatures) { uint nonce; (signatures, nonce) = getDataTrackingParameters(TOKEN_INFO_DATA_INDEX); return(signatures); } function getTokenInfoNonce() public view returns(uint nonce) { address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(TOKEN_INFO_DATA_INDEX); return nonce; } function setValidDurationData(uint validDurationBlocks) public onlyOperator { require(validDurationBlocks > 5); setNewData(VALID_DURATION_DATA_INDEX); validDurationData.durationInBlocks = validDurationBlocks; } function approveValidDurationData(uint nonce) public onlyOperator { if (addSignature(VALID_DURATION_DATA_INDEX, nonce, msg.sender)) { conversionRates.setValidRateDurationInBlocks(validDurationData.durationInBlocks); } } function approveValidDurationData(uint nonce) public onlyOperator { if (addSignature(VALID_DURATION_DATA_INDEX, nonce, msg.sender)) { conversionRates.setValidRateDurationInBlocks(validDurationData.durationInBlocks); } } function getValidDurationBlocksData() public view returns(uint validDuration, uint nonce) { address[] memory signatures; (signatures, nonce) = getDataTrackingParameters(VALID_DURATION_DATA_INDEX); return(nonce, validDurationData.durationInBlocks); } function getValidDurationSignatures() public view returns (address[] memory signatures) { uint nonce; (signatures, nonce) = getDataTrackingParameters(VALID_DURATION_DATA_INDEX); return(signatures); } function performAddToken() internal { conversionRates.addToken(addTokenData.token); conversionRates.addOperator(this); conversionRates.setTokenControlInfo( addTokenData.token, addTokenData.minimalResolution, addTokenData.maxPerBlockImbalance, addTokenData.maxTotalImbalance ); int[] memory zeroArr = new int[](1); zeroArr[0] = 0; conversionRates.setQtyStepFunction(addTokenData.token, zeroArr, zeroArr, zeroArr, zeroArr); conversionRates.setImbalanceStepFunction(addTokenData.token, zeroArr, zeroArr, zeroArr, zeroArr); conversionRates.enableTokenTrade(addTokenData.token); conversionRates.removeOperator(this); } function performSetTokenControlInfo() internal { require(tokenControlInfoData.tokens.length == tokenControlInfoData.perBlockImbalance.length); require(tokenControlInfoData.tokens.length == tokenControlInfoData.maxTotalImbalance.length); uint minRecordResolution; for (uint i = 0; i < tokenControlInfoData.tokens.length; i++) { uint maxPerBlock; uint maxTotal; (minRecordResolution, maxPerBlock, maxTotal) = conversionRates.getTokenControlInfo(tokenControlInfoData.tokens[i]); require(minRecordResolution != 0); conversionRates.setTokenControlInfo(tokenControlInfoData.tokens[i], minRecordResolution, tokenControlInfoData.perBlockImbalance[i], tokenControlInfoData.maxTotalImbalance[i]); } } function performSetTokenControlInfo() internal { require(tokenControlInfoData.tokens.length == tokenControlInfoData.perBlockImbalance.length); require(tokenControlInfoData.tokens.length == tokenControlInfoData.maxTotalImbalance.length); uint minRecordResolution; for (uint i = 0; i < tokenControlInfoData.tokens.length; i++) { uint maxPerBlock; uint maxTotal; (minRecordResolution, maxPerBlock, maxTotal) = conversionRates.getTokenControlInfo(tokenControlInfoData.tokens[i]); require(minRecordResolution != 0); conversionRates.setTokenControlInfo(tokenControlInfoData.tokens[i], minRecordResolution, tokenControlInfoData.perBlockImbalance[i], tokenControlInfoData.maxTotalImbalance[i]); } } }
12,833,680
[ 1, 1289, 1147, 1472, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4266, 6814, 4727, 353, 18735, 2171, 288, 203, 203, 565, 16401, 20836, 2713, 4105, 20836, 31, 203, 203, 565, 1958, 1436, 1345, 751, 288, 203, 3639, 4232, 39, 3462, 377, 1147, 31, 203, 3639, 2254, 1377, 943, 5269, 1170, 12296, 31, 203, 565, 289, 203, 203, 565, 1436, 1345, 751, 2713, 527, 1345, 751, 31, 203, 203, 565, 1958, 3155, 3367, 966, 751, 288, 203, 3639, 4232, 39, 3462, 8526, 2430, 31, 203, 3639, 2254, 8526, 943, 5269, 1170, 12296, 31, 203, 565, 289, 203, 203, 565, 3155, 3367, 966, 751, 2713, 1147, 3367, 966, 751, 31, 203, 203, 565, 1958, 2364, 5326, 751, 288, 203, 3639, 2254, 3734, 382, 6450, 31, 203, 565, 289, 203, 203, 565, 2364, 5326, 751, 2713, 923, 5326, 751, 31, 203, 203, 565, 2254, 5381, 2713, 14275, 67, 5923, 67, 4883, 67, 9199, 273, 404, 31, 203, 565, 2254, 5381, 2713, 15093, 67, 24951, 67, 4883, 67, 9199, 273, 576, 31, 203, 565, 2254, 5381, 2713, 9443, 67, 4883, 67, 9199, 273, 890, 31, 203, 203, 565, 2254, 5381, 2713, 11689, 67, 8412, 67, 4883, 67, 9199, 273, 374, 31, 203, 565, 445, 4266, 6814, 4727, 12, 6814, 20836, 389, 20990, 20836, 16, 1758, 389, 3666, 13, 1071, 203, 3639, 18735, 2171, 12, 5041, 3621, 12, 2867, 24899, 20990, 20836, 13, 3631, 389, 3666, 16, 9443, 67, 4883, 67, 9199, 13, 203, 565, 288, 203, 3639, 2583, 24899, 20990, 20836, 480, 1758, 12, 20, 10019, 203, 3639, 4105, 20836, 273, 389, 20990, 20836, 31, 203, 565, 289, 2 ]
./full_match/3/0x7b99dB7b89BfB78183569864A86A71FF4cD1b571/sources/browser/TKBAirpool.sol
add stake amount to sum of all stakes across al lps
totalStakedAmount = totalStakedAmount.add(amountToken);
8,217,209
[ 1, 1289, 384, 911, 3844, 358, 2142, 434, 777, 384, 3223, 10279, 524, 328, 1121, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 510, 9477, 6275, 273, 2078, 510, 9477, 6275, 18, 1289, 12, 8949, 1345, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice Math library that facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision. /// @author Adapted from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/FullMath.sol. /// @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 an 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) { unchecked { // 512-bit multiply [prod1 prod0] = a * b. // Compute the product mod 2**256 and mod 2**256 - 1, // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0. uint256 prod0; // Least significant 256 bits of the product. uint256 prod1; // Most significant 256 bits of the product. assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256 - // also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] - // compute remainder using mulmod. uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number. assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator - // compute largest power of two divisor of denominator // (always >= 1). uint256 twos = uint256(-int256(denominator)) & denominator; // Divide denominator by power of two. assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two. assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos - // if twos is zero, then it becomes one. assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 - // now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // for four bits. That is, denominator * inv = 1 mod 2**4. uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // Inverse mod 2**8. inv *= 2 - denominator * inv; // Inverse mod 2**16. inv *= 2 - denominator * inv; // Inverse mod 2**32. inv *= 2 - denominator * inv; // Inverse mod 2**64. inv *= 2 - denominator * inv; // Inverse mod 2**128. inv *= 2 - denominator * inv; // Inverse mod 2**256. // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision - throws if result overflows an 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); unchecked { if (mulmod(a, b, denominator) != 0) { require(result < type(uint256).max); result++; } } } }
@notice Calculates ceil(a×b÷denominator) with full precision - throws if result overflows an 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); unchecked { if (mulmod(a, b, denominator) != 0) { require(result < type(uint256).max); result++; } } }
1,054,938
[ 1, 10587, 8416, 12, 69, 132, 250, 70, 132, 120, 13002, 26721, 13, 598, 1983, 6039, 300, 1216, 309, 563, 9391, 87, 392, 2254, 5034, 578, 15030, 422, 374, 18, 225, 279, 1021, 3309, 1780, 464, 18, 225, 324, 1021, 15027, 18, 225, 15030, 1021, 15013, 18, 327, 563, 1021, 8303, 17, 3682, 563, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14064, 7244, 11066, 310, 1211, 12, 203, 3639, 2254, 5034, 279, 16, 203, 3639, 2254, 5034, 324, 16, 203, 3639, 2254, 5034, 15030, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 563, 13, 288, 203, 3639, 563, 273, 14064, 7244, 12, 69, 16, 324, 16, 15030, 1769, 203, 565, 22893, 288, 203, 3639, 309, 261, 16411, 1711, 12, 69, 16, 324, 16, 15030, 13, 480, 374, 13, 288, 203, 5411, 2583, 12, 2088, 411, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 5411, 563, 9904, 31, 203, 3639, 289, 203, 565, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x5890301587c4f9099d5ed4041cfc4bff332357a9 //Contract name: ICOContract //Balance: 0 Ether //Verification Date: 2/13/2018 //Transacion Count: 8 // CODE STARTS HERE pragma solidity ^0.4.16; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Base { modifier only(address allowed) { require(msg.sender == allowed); _; } } contract Owned is Base { address public owner; address newOwner; function Owned() public { owner = msg.sender; } function transferOwnership(address _newOwner) only(owner) public { newOwner = _newOwner; } function acceptOwnership() only(newOwner) public { OwnershipTransferred(owner, newOwner); owner = newOwner; } event OwnershipTransferred(address indexed _from, address indexed _to); } contract ERC20 is Owned { using SafeMath for uint; bool public isStarted = false; modifier isStartedOnly() { require(isStarted); _; } modifier isNotStartedOnly() { require(!isStarted); _; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) isStartedOnly public returns (bool success) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) isStartedOnly public returns (bool success) { require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner]; } function approve_fixed(address _spender, uint _currentValue, uint _value) isStartedOnly public returns (bool success) { if(allowed[msg.sender][_spender] == _currentValue){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } else { return false; } } function approve(address _spender, uint _value) isStartedOnly public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint remaining) { return allowed[_owner][_spender]; } mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; } contract Token is ERC20 { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; function Token(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function start() public only(owner) isNotStartedOnly { isStarted = true; } //================= Crowdsale Only ================= function mint(address _to, uint _amount) public only(owner) isNotStartedOnly returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } function multimint(address[] dests, uint[] values) public only(owner) isNotStartedOnly returns (uint) { uint i = 0; while (i < dests.length) { mint(dests[i], values[i]); i += 1; } return(i); } } contract TokenWithoutStart is Owned { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; uint public totalSupply; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function TokenWithoutStart(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address _to, uint _value) public returns (bool success) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner]; } function approve_fixed(address _spender, uint _currentValue, uint _value) public returns (bool success) { if(allowed[msg.sender][_spender] == _currentValue){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } else { return false; } } function approve(address _spender, uint _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint remaining) { return allowed[_owner][_spender]; } mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; function mint(address _to, uint _amount) public only(owner) returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } function multimint(address[] dests, uint[] values) public only(owner) returns (uint) { uint i = 0; while (i < dests.length) { mint(dests[i], values[i]); i += 1; } return(i); } } contract ICOContract { address public projectWallet; //beneficiary wallet address public operator = 0x4C67EB86d70354731f11981aeE91d969e3823c39; //address of the ICO operator — the one who adds milestones and InvestContracts uint public constant waitPeriod = 7 days; //wait period after milestone finish and untile the next one can be started address[] public pendingInvestContracts = [0x0]; //pending InvestContracts not yet accepted by the project mapping(address => uint) public pendingInvestContractsIndices; address[] public investContracts = [0x0]; // accepted InvestContracts mapping(address => uint) public investContractsIndices; uint public minimalInvestment = 5 ether; uint public totalEther; // How much Ether is collected =sum of all milestones' etherAmount uint public totalToken; // how many tokens are distributed = sum of all milestones' tokenAmount uint public tokenLeft; uint public etherLeft; Token public token; ///ICO caps uint public minimumCap; // set in constructor uint public maximumCap; // set in constructor //Structure for milestone struct Milestone { uint etherAmount; //how many Ether is needed for this milestone uint tokenAmount; //how many tokens releases this milestone uint startTime; //real time when milestone has started, set upon start uint finishTime; //real time when milestone has finished, set upon finish uint duration; //assumed duration for milestone implementation, set upon milestone creation string description; string results; } Milestone[] public milestones; uint public currentMilestone; uint public sealTimestamp; //Until when it's possible to add new and change existing milestones modifier only(address _sender) { require(msg.sender == _sender); _; } modifier notSealed() { require(now <= sealTimestamp); _; } modifier sealed() { require(now > sealTimestamp); _; } /// @dev Create an ICOContract. /// @param _tokenAddress Address of project token contract /// @param _projectWallet Address of project developers wallet /// @param _sealTimestamp Until this timestamp it's possible to alter milestones /// @param _minimumCap Wei value of minimum cap for responsible ICO /// @param _maximumCap Wei value of maximum cap for responsible ICO function ICOContract(address _tokenAddress, address _projectWallet, uint _sealTimestamp, uint _minimumCap, uint _maximumCap) public { token = Token(_tokenAddress); projectWallet = _projectWallet; sealTimestamp = _sealTimestamp; minimumCap = _minimumCap; maximumCap = _maximumCap; } //MILESTONES /// @dev Adds a milestone. /// @param _etherAmount amount of Ether needed for the added milestone /// @param _tokenAmount amount of tokens which will be released for added milestone /// @param _startTime field for start timestamp of added milestone /// @param _duration assumed duration of the milestone /// @param _description description of added milestone /// @param _result result description of added milestone function addMilestone(uint _etherAmount, uint _tokenAmount, uint _startTime, uint _duration, string _description, string _result) notSealed only(operator) public returns(uint) { totalEther += _etherAmount; totalToken += _tokenAmount; return milestones.push(Milestone(_etherAmount, _tokenAmount, _startTime, 0, _duration, _description, _result)); } /// @dev Edits milestone by given id and new parameters. /// @param _id id of editing milestone /// @param _etherAmount amount of Ether needed for the milestone /// @param _tokenAmount amount of tokens which will be released for the milestone /// @param _startTime start timestamp of the milestone /// @param _duration assumed duration of the milestone /// @param _description description of the milestone /// @param _results result description of the milestone function editMilestone(uint _id, uint _etherAmount, uint _tokenAmount, uint _startTime, uint _duration, string _description, string _results) notSealed only(operator) public { require(_id < milestones.length); totalEther = totalEther - milestones[_id].etherAmount + _etherAmount; totalToken = totalToken - milestones[_id].tokenAmount + _tokenAmount; milestones[_id].etherAmount = _etherAmount; milestones[_id].tokenAmount = _tokenAmount; milestones[_id].startTime = _startTime; milestones[_id].duration = _duration; milestones[_id].description = _description; milestones[_id].results = _results; } //TODO: add check if ICOContract has tokens ///@dev Seals milestone making them no longer changeable. Works by setting changeable timestamp to the current one, //so in future it would be no longer callable. function seal() only(operator) notSealed() public { assert(milestones.length > 0); //assert(token.balanceOf(address(this)) >= totalToken; sealTimestamp = now; etherLeft = totalEther; tokenLeft = totalToken; } function finishMilestone(string _results) only(operator) public { var milestone = getCurrentMilestone(); milestones[milestone].finishTime = now; milestones[milestone].results = _results; } function startNextMilestone() public only(operator) { uint milestone = getCurrentMilestone(); require(milestones[currentMilestone].finishTime == 0); currentMilestone +=1; milestones[currentMilestone].startTime = now; for(uint i=1; i < investContracts.length; i++) { InvestContract investContract = InvestContract(investContracts[i]); investContract.milestoneStarted(milestone); } } ///@dev Returns number of the current milestone. Starts from 1. 0 indicates that project implementation has not started yet. function getCurrentMilestone() public constant returns(uint) { /* for(uint i=0; i < milestones.length; i++) { if (milestones[i].startTime <= now && now <= milestones[i].finishTime + waitPeriod) { return i+1; } } return 0; */ return currentMilestone; } /// @dev Getter function for length. For testing purposes. function milestonesLength() public view returns(uint) { return milestones.length; } ///InvestContract part function createInvestContract(address _investor, uint _etherAmount, uint _tokenAmount) public sealed only(operator) returns(address) { require(_etherAmount >= minimalInvestment); //require(milestones[0].startTime - now >= 5 days); //require(maximumCap >= _etherAmount + investorEther); //require(token.balanceOf(address(this)) >= _tokenAmount + investorTokens); address investContract = new InvestContract(address(this), _investor, _etherAmount, _tokenAmount); pendingInvestContracts.push(investContract); pendingInvestContractsIndices[investContract]=(pendingInvestContracts.length-1); //note that indices start from 1 return(investContract); } /// @dev This function is called by InvestContract when it receives Ether. It shold move this InvestContract from pending to the real ones. function investContractDeposited() public { //require(maximumCap >= investEthAmount + investorEther); uint index = pendingInvestContractsIndices[msg.sender]; assert(index > 0); uint len = pendingInvestContracts.length; InvestContract investContract = InvestContract(pendingInvestContracts[index]); pendingInvestContracts[index] = pendingInvestContracts[len-1]; pendingInvestContracts.length = len-1; investContracts.push(msg.sender); investContractsIndices[msg.sender]=investContracts.length-1; //note that indexing starts from 1 uint investmentToken = investContract.tokenAmount(); uint investmentEther = investContract.etherAmount(); etherLeft -= investmentEther; tokenLeft -= investmentToken; assert(token.transfer(msg.sender, investmentToken)); } function returnTokens() public only(operator) { uint balance = token.balanceOf(address(this)); token.transfer(projectWallet, balance); } } contract Pullable { using SafeMath for uint256; mapping(address => uint256) public payments; /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayment() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); payments[payee] = 0; assert(payee.send(payment)); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param _destination The destination address of the funds. * @param _amount The amount to transfer. */ function asyncSend(address _destination, uint256 _amount) internal { payments[_destination] = payments[_destination].add(_amount); } } contract TokenPullable { using SafeMath for uint256; Token public token; mapping(address => uint256) public tokenPayments; function TokenPullable(address _ico) public { ICOContract icoContract = ICOContract(_ico); token = icoContract.token(); } /** * @dev withdraw accumulated balance, called by payee. */ function withdrawTokenPayment() public { address tokenPayee = msg.sender; uint256 tokenPayment = tokenPayments[tokenPayee]; require(tokenPayment != 0); require(token.balanceOf(address(this)) >= tokenPayment); tokenPayments[tokenPayee] = 0; assert(token.transfer(tokenPayee, tokenPayment)); } function asyncTokenSend(address _destination, uint _amount) internal { tokenPayments[_destination] = tokenPayments[_destination].add(_amount); } } contract InvestContract is TokenPullable, Pullable { address public projectWallet; // person from ico team address public investor; uint public arbiterAcceptCount = 0; uint public quorum; ICOContract public icoContract; //Token public token; uint[] public etherPartition; //weis uint[] public tokenPartition; //tokens //Each arbiter has parameter delay which equals time interval in seconds betwwen dispute open and when the arbiter can vote struct ArbiterInfo { uint index; bool accepted; uint voteDelay; } mapping(address => ArbiterInfo) public arbiters; //arbiterAddress => ArbiterInfo{acceptance, voteDelay} address[] public arbiterList = [0x0]; //it's needed to show complete arbiter list //this structure can be optimized struct Dispute { uint timestamp; string reason; address[5] voters; mapping(address => address) votes; uint votesProject; uint votesInvestor; } mapping(uint => Dispute) public disputes; uint public etherAmount; //How much Ether investor wants to invest uint public tokenAmount; //How many tokens investor wants to receive bool public disputing=false; uint public amountToPay; //investAmount + commissions //Modifier that restricts function caller modifier only(address _sender) { require(msg.sender == _sender); _; } modifier onlyArbiter() { require(arbiters[msg.sender].voteDelay > 0); _; } function InvestContract(address _ICOContractAddress, address _investor, uint _etherAmount, uint _tokenAmount) TokenPullable(_ICOContractAddress) public { icoContract = ICOContract(_ICOContractAddress); token = icoContract.token(); etherAmount = _etherAmount; tokenAmount = _tokenAmount; projectWallet = icoContract.projectWallet(); investor = _investor; amountToPay = etherAmount*101/100; //101% of the agreed amount quorum = 3; //hardcoded arbiters addAcceptedArbiter(0x42efbba0563AE5aa2312BeBce1C18C6722B67857, 1); //Ryan addAcceptedArbiter(0x37D5953c24a2efD372C97B06f22416b68e896eaf, 1);// Maxim Telegin addAcceptedArbiter(0xd0D2e05Fd34d566612529512F7Af1F8a60EDAb6C, 1);// Vladimir Dyakin addAcceptedArbiter(0xB6508aFaCe815e481bf3B3Fa9B4117D46C963Ec3, 1);// Immánuel Fodor addAcceptedArbiter(0x73380dc12B629FB7fBD221E05D25E42f5f3FAB11, 1);// Alban arbiterAcceptCount = 5; uint milestoneEtherAmount; //How much Ether does investor send for a milestone uint milestoneTokenAmount; //How many Tokens does investor receive for a milestone uint milestoneEtherTarget; //How much TOTAL Ether a milestone needs uint milestoneTokenTarget; //How many TOTAL tokens a milestone releases uint totalEtherInvestment; uint totalTokenInvestment; for(uint i=0; i<icoContract.milestonesLength(); i++) { (milestoneEtherTarget, milestoneTokenTarget, , , , , ) = icoContract.milestones(i); milestoneEtherAmount = _etherAmount * milestoneEtherTarget / icoContract.totalEther(); milestoneTokenAmount = _tokenAmount * milestoneTokenTarget / icoContract.totalToken(); totalEtherInvestment += milestoneEtherAmount; //used to prevent rounding errors totalTokenInvestment += milestoneTokenAmount; //used to prevent rounding errors etherPartition.push(milestoneEtherAmount); tokenPartition.push(milestoneTokenAmount); } etherPartition[0] += _etherAmount - totalEtherInvestment; //rounding error is added to the first milestone tokenPartition[0] += _tokenAmount - totalTokenInvestment; //rounding error is added to the first milestone } function() payable public only(investor) { require(arbiterAcceptCount >= quorum); require(msg.value == amountToPay); require(getCurrentMilestone() == 0); //before first icoContract.investContractDeposited(); } //Adding an arbiter which has already accepted his participation in ICO. function addAcceptedArbiter(address _arbiter, uint _delay) internal { require(token.balanceOf(address(this))==0); //only callable when there are no tokens at this contract require(_delay > 0); //to differ from non-existent arbiters var index = arbiterList.push(_arbiter); arbiters[_arbiter] = ArbiterInfo(index, true, _delay); } /* Not used for our own ICO as arbiters are the same and already accepted their participation function arbiterAccept() public onlyArbiter { require(!arbiters[msg.sender].accepted); arbiters[msg.sender].accepted = true; arbiterAcceptCount += 1; } function addArbiter(address _arbiter, uint _delay) public { //only(investor) require(token.balanceOf(address(this))==0); //only callable when there are no tokens at this contract require(_delay > 0); //to differ from non-existent arbiters var index = arbiterList.push(_arbiter); arbiters[_arbiter] = ArbiterInfo(index, false, _delay); } */ function vote(address _voteAddress) public onlyArbiter { require(_voteAddress == investor || _voteAddress == projectWallet); require(disputing); uint milestone = getCurrentMilestone(); require(milestone > 0); require(disputes[milestone].votes[msg.sender] == 0); require(now - disputes[milestone].timestamp >= arbiters[msg.sender].voteDelay); //checking if enough time has passed since dispute had been opened disputes[milestone].votes[msg.sender] = _voteAddress; disputes[milestone].voters[disputes[milestone].votesProject+disputes[milestone].votesInvestor] = msg.sender; if (_voteAddress == projectWallet) { disputes[milestone].votesProject += 1; } else if (_voteAddress == investor) { disputes[milestone].votesInvestor += 1; } else { revert(); } if (disputes[milestone].votesProject >= quorum) { executeVerdict(true); } if (disputes[milestone].votesInvestor >= quorum) { executeVerdict(false); } } function executeVerdict(bool _projectWon) internal { //uint milestone = getCurrentMilestone(); disputing = false; if (_projectWon) { //token.transfer(0x0, token.balanceOf(address(this))); } else { //asyncTokenSend(investor, tokensToSend); //asyncSend(projectWallet, etherToSend); //token.transfer(address(icoContract), token.balanceOf(this)); // send all tokens back } } function openDispute(string _reason) public only(investor) { assert(!disputing); var milestone = getCurrentMilestone(); assert(milestone > 0); disputing = true; disputes[milestone].timestamp = now; disputes[milestone].reason = _reason; } function milestoneStarted(uint _milestone) public only(address(icoContract)) { require(!disputing); var etherToSend = etherPartition[_milestone]; var tokensToSend = tokenPartition[_milestone]; //async send asyncSend(projectWallet, etherToSend); asyncTokenSend(investor, tokensToSend); } function getCurrentMilestone() public constant returns(uint) { return icoContract.getCurrentMilestone(); } }
set in constructor
uint public maximumCap;
14,122,522
[ 1, 542, 316, 3885, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 4207, 4664, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at BscScan.com on 2021-08-24 */ // 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; } } /** * @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 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()); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @dev 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); } 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; } } /** * @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); } } } } /** * @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' 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"); } } } interface IZaiReferral { /** * @dev Record referral. */ function recordReferral(address user, address referrer) external; /** * @dev Record referral commission. */ function recordReferralCommission(address referrer, uint256 commission) external; /** * @dev Get the referrer address that referred the user. */ function getReferrer(address user) external view returns (address); } 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 ); } pragma abicoder v2; /** * @title Zai Option - forked from PancakePredictionV2 */ contract zaiOption is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; AggregatorV3Interface public oracle; bool public genesisLockOnce = false; bool public genesisStartOnce = false; address public adminAddress; // address of the admin address public operatorAddress; // address of the operator uint256 public bufferSeconds; // number of seconds for valid execution of a prediction round uint256 public intervalSeconds; // interval in seconds between two prediction rounds uint256 public minBetAmount; // minimum betting amount (denominated in wei) uint256 public treasuryFee; // treasury rate (e.g. 200 = 2%, 150 = 1.50%) uint256 public treasuryAmount; // treasury amount that was not claimed // Operational Addresses // address public treasuryAddress = 0xBe511eF95e14E0524aA86187B233cffDBA87aB98; address public devAddress = 0x8bC8B45626b43d5F63D79D6002B1bA730B70F88a; address public staffAddress = 0x0926345c8Eb1206461F49cCF213ca52B46e34429; // address public buybackAddress = 0x5bA4b2E88ea7303aa25c0798B28e107d129A2A2a; address public Maintenance = 0xa7F749B90BDbDe8d2C0EC61a952914C88D863027; uint256 public currentEpoch; // current epoch for prediction round uint256 public oracleLatestRoundId; // converted from uint80 (Chainlink) uint256 public oracleUpdateAllowance; // seconds uint256 public constant MAX_TREASURY_FEE = 1000; // 10% uint256 public passedBlocks = 200480; // 1 week of blocks uint256 public jackpotLock = 0; // blockNumber for counting // ZAIF FEE Calculation uint16 public constant TaxFee = 500; // 2% for referral payments uint16 public constant refFee = 200; // Zai referral contract address. IZaiReferral public zaiReferral; // Referral commission rate in basis points. uint16 public referralCommissionRate = 200; //jackpot Acumulation Amount uint256 public jackpotAcmAmt; uint256 public jackpotAcmSafeCheck; mapping(uint256 => mapping(address => BetInfo)) public ledger; mapping(uint256 => Round) public rounds; mapping(uint256 => RoundJackpotInfo) public roundsInfo; mapping(address => uint256[]) public userRounds; enum Position { Bull, Bear } struct Round { uint256 epoch; uint256 startTimestamp; uint256 lockTimestamp; uint256 closeTimestamp; int256 lockPrice; int256 closePrice; uint256 lockOracleId; uint256 closeOracleId; uint256 totalAmount; uint256 bullAmount; uint256 bearAmount; uint256 rewardBaseCalAmount; uint256 rewardAmount; bool oracleCalled; } struct RoundJackpotInfo { uint256 epoch; bool jackpotRound; bool jackpotClaimed; } struct BetInfo { Position position; uint256 amount; bool claimed; // default false } event BetBear(address indexed sender, uint256 indexed epoch, uint256 amount); event BetBull(address indexed sender, uint256 indexed epoch, uint256 amount); event Claim(address indexed sender, uint256 indexed epoch, uint256 amount); event EndRound(uint256 indexed epoch, uint256 indexed roundId, int256 price); event LockRound(uint256 indexed epoch, uint256 indexed roundId, int256 price); event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount); event NewAdminAddress(address admin); event NewBufferAndIntervalSeconds(uint256 bufferSeconds, uint256 intervalSeconds); event NewMinBetAmount(uint256 indexed epoch, uint256 minBetAmount); event NewTreasuryFee(uint256 indexed epoch, uint256 treasuryFee); event NewOperatorAddress(address operator); event NewOracle(address oracle); event NewOracleUpdateAllowance(uint256 oracleUpdateAllowance); event Pause(uint256 indexed epoch); event RewardsCalculated( uint256 indexed epoch, uint256 rewardBaseCalAmount, uint256 rewardAmount, uint256 treasuryAmount ); event StartRound(uint256 indexed epoch); event TokenRecovery(address indexed token, uint256 amount); event TreasuryClaim(uint256 amount); event Unpause(uint256 indexed epoch); IERC20 public zaif; modifier onlyAdmin() { require(msg.sender == adminAddress, "Not admin"); _; } modifier onlyAdminOrOperator() { require(msg.sender == adminAddress || msg.sender == operatorAddress, "Not operator/admin"); _; } modifier onlyOperator() { require(msg.sender == operatorAddress, "Not operator"); _; } modifier notContract() { require(!_isContract(msg.sender), "Contract not allowed"); require(msg.sender == tx.origin, "Proxy contract not allowed"); _; } /** * @notice Constructor * @param _oracleAddress: oracle address * @param _adminAddress: admin address * @param _operatorAddress: operator address * @param _intervalSeconds: number of time within an interval * @param _bufferSeconds: buffer of time for resolution of price * @param _minBetAmount: minimum bet amounts (in wei) * @param _oracleUpdateAllowance: oracle update allowance * @param _treasuryFee: treasury fee (1000 = 10%) */ constructor( address _oracleAddress, address _adminAddress, address _operatorAddress, uint256 _intervalSeconds, uint256 _bufferSeconds, uint256 _minBetAmount, uint256 _oracleUpdateAllowance, uint256 _treasuryFee ) { require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high"); oracle = AggregatorV3Interface(_oracleAddress); adminAddress = _adminAddress; operatorAddress = _operatorAddress; intervalSeconds = _intervalSeconds; bufferSeconds = _bufferSeconds; minBetAmount = _minBetAmount; oracleUpdateAllowance = _oracleUpdateAllowance; treasuryFee = _treasuryFee; } // Set the token contract address function setzaiAddress(IERC20 zaifAddress) public onlyOwner { zaif = zaifAddress; } // Set the maintenance address function setMaintenance(address _maintenance) public onlyOwner { Maintenance = _maintenance; } /** * @notice Bet bear position * @param epoch: epoch */ function betBear(uint256 epoch,address _referrer ,uint256 amount) external whenNotPaused nonReentrant notContract { require(epoch == currentEpoch, "Bet is too early/late"); require(_bettable(epoch), "Round not bettable"); require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount"); require(ledger[epoch][msg.sender].amount == 0, "Can only bet once per round"); //Calculate token tax fees uint256 taxAmount = amount.mul(TaxFee).div(10000); uint256 taxedAmount = amount - taxAmount; //Record Referral if (amount > 0 && address(zaiReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender) { zaiReferral.recordReferral(msg.sender, _referrer); } // Update round data Round storage round = rounds[epoch]; RoundJackpotInfo storage roundInfo = roundsInfo[epoch]; // JackPot check if(jackpotLock != 0){ if(block.number >= jackpotLock + passedBlocks){ round.totalAmount = round.totalAmount + taxedAmount + jackpotAcmAmt; jackpotLock = 0; jackpotAcmAmt = 0; roundInfo.jackpotRound = true; }else{ round.totalAmount = round.totalAmount + taxedAmount; } }else{ round.totalAmount = round.totalAmount + taxedAmount; } round.bearAmount = round.bearAmount + taxedAmount; // Update user data BetInfo storage betInfo = ledger[epoch][msg.sender]; betInfo.position = Position.Bear; betInfo.amount += taxedAmount; userRounds[msg.sender].push(epoch); zaif.transferFrom(msg.sender,address(this),amount); emit BetBear(msg.sender, epoch, amount); } /** * @notice Bet bull position * @param epoch: epoch */ function betBull(uint256 epoch,address _referrer, uint256 amount) external whenNotPaused nonReentrant notContract { require(epoch == currentEpoch, "Bet is too early/late"); require(_bettable(epoch), "Round not bettable"); require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount"); require(ledger[epoch][msg.sender].amount == 0, "Can only bet once per round"); //Calculate token tax fees uint256 taxAmount = amount.mul(TaxFee).div(10000); uint256 taxedAmount = amount - taxAmount; //Record Referral if (amount > 0 && address(zaiReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender) { zaiReferral.recordReferral(msg.sender, _referrer); } // Update round data Round storage round = rounds[epoch]; RoundJackpotInfo storage roundInfo = roundsInfo[epoch]; // JackPot check if(jackpotLock != 0){ if(block.number >= jackpotLock + passedBlocks){ round.totalAmount = round.totalAmount + taxedAmount + jackpotAcmAmt; jackpotLock = 0; jackpotAcmAmt = 0; roundInfo.jackpotRound = true; }else{ round.totalAmount = round.totalAmount + taxedAmount; } }else{ round.totalAmount = round.totalAmount + taxedAmount; } round.bullAmount = round.bullAmount + taxedAmount; // Update user data BetInfo storage betInfo = ledger[epoch][msg.sender]; betInfo.position = Position.Bull; betInfo.amount = taxedAmount; userRounds[msg.sender].push(epoch); zaif.transferFrom(msg.sender,address(this),amount); emit BetBull(msg.sender, epoch, amount); } /** * @notice Claim reward for an array of epochs * @param epochs: array of epochs */ function claim(uint256[] calldata epochs) external nonReentrant notContract { uint256 reward; // Initializes reward for (uint256 i = 0; i < epochs.length; i++) { require(rounds[epochs[i]].startTimestamp != 0, "Round has not started"); require(block.timestamp > rounds[epochs[i]].closeTimestamp, "Round has not ended"); uint256 addedReward = 0; // Round valid, claim rewards if (rounds[epochs[i]].oracleCalled) { require(claimable(epochs[i], msg.sender), "Not eligible for claim"); Round memory round = rounds[epochs[i]]; RoundJackpotInfo memory roundInfo = roundsInfo[epochs[i]]; if (roundInfo.jackpotRound == true) { if(roundInfo.jackpotClaimed == false){ jackpotAcmSafeCheck = 0; roundInfo.jackpotClaimed = true; } } addedReward = (ledger[epochs[i]][msg.sender].amount * round.rewardAmount) / round.rewardBaseCalAmount; uint256 ReferralAmt = (addedReward * refFee) / 10000; payReferralCommission(msg.sender,addedReward); addedReward = addedReward - ReferralAmt; } // Round invalid, refund bet amount else { require(refundable(epochs[i], msg.sender), "Not eligible for refund"); if (roundsInfo[epochs[i]].jackpotRound == true) { if(roundsInfo[epochs[i]].jackpotClaimed == false){ jackpotAcmAmt = jackpotAcmSafeCheck; roundsInfo[epochs[i]].jackpotClaimed = true; } } addedReward = ledger[epochs[i]][msg.sender].amount; } ledger[epochs[i]][msg.sender].claimed = true; reward += addedReward; emit Claim(msg.sender, epochs[i], addedReward); } if (reward > 0) { IERC20(zaif).safeTransfer(msg.sender,reward); } } /** * @notice Start the next round n, lock price for round n-1, end round n-2 * @dev Callable by operator */ function executeRound() external whenNotPaused onlyOperator { require( genesisStartOnce && genesisLockOnce, "Can only run after genesisStartRound and genesisLockRound is triggered" ); (uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle(); oracleLatestRoundId = uint256(currentRoundId); // CurrentEpoch refers to previous round (n-1) _safeLockRound(currentEpoch, currentRoundId, currentPrice); _safeEndRound(currentEpoch - 1, currentRoundId, currentPrice); _calculateRewards(currentEpoch - 1); // Increment currentEpoch to current round (n) currentEpoch = currentEpoch + 1; _safeStartRound(currentEpoch); } /** * @notice Lock genesis round * @dev Callable by operator */ function genesisLockRound() external whenNotPaused onlyOperator { require(genesisStartOnce, "Can only run after genesisStartRound is triggered"); require(!genesisLockOnce, "Can only run genesisLockRound once"); (uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle(); oracleLatestRoundId = uint256(currentRoundId); _safeLockRound(currentEpoch, currentRoundId, currentPrice); currentEpoch = currentEpoch + 1; _startRound(currentEpoch); genesisLockOnce = true; } /** * @notice Start genesis round * @dev Callable by admin or operator */ function genesisStartRound() external whenNotPaused onlyOperator { require(!genesisStartOnce, "Can only run genesisStartRound once"); currentEpoch = currentEpoch + 1; _startRound(currentEpoch); genesisStartOnce = true; } /** * @notice called by the admin to pause, triggers stopped state * @dev Callable by admin or operator */ function pause() external whenNotPaused onlyAdminOrOperator { _pause(); emit Pause(currentEpoch); } /** * @notice Claim all rewards in treasury * @dev Callable by admin */ function claimTreasury() external nonReentrant onlyAdmin { uint256 currentTreasuryAmount = treasuryAmount; treasuryAmount = 0; uint256 maintenanceAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3% uint256 devAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3% uint256 staffAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3% // IERC20(zaif).safeTransfer(treasuryAddress,treasuryAmt); IERC20(zaif).safeTransfer(devAddress, devAmt); IERC20(zaif).safeTransfer(staffAddress, staffAmt); IERC20(zaif).safeTransfer(Maintenance, maintenanceAmt); emit TreasuryClaim(currentTreasuryAmount); } /** * @notice called by the admin to unpause, returns to normal state * Reset genesis state. Once paused, the rounds would need to be kickstarted by genesis */ function unpause() external whenPaused onlyAdmin { genesisStartOnce = false; genesisLockOnce = false; _unpause(); emit Unpause(currentEpoch); } /** * @notice Set buffer and interval (in seconds) * @dev Callable by admin */ function setBufferAndIntervalSeconds(uint256 _bufferSeconds, uint256 _intervalSeconds) external whenPaused onlyAdmin { require(_bufferSeconds < _intervalSeconds, "bufferSeconds must be inferior to intervalSeconds"); bufferSeconds = _bufferSeconds; intervalSeconds = _intervalSeconds; emit NewBufferAndIntervalSeconds(_bufferSeconds, _intervalSeconds); } /** * @notice Set minBetAmount * @dev Callable by admin */ function setMinBetAmount(uint256 _minBetAmount) external whenPaused onlyAdmin { require(_minBetAmount != 0, "Must be superior to 0"); minBetAmount = _minBetAmount; emit NewMinBetAmount(currentEpoch, minBetAmount); } /** * @notice Set operator address * @dev Callable by admin */ function setOperator(address _operatorAddress) external onlyAdmin { require(_operatorAddress != address(0), "Cannot be zero address"); operatorAddress = _operatorAddress; emit NewOperatorAddress(_operatorAddress); } /** * @notice Set Oracle address * @dev Callable by admin */ function setOracle(address _oracle) external whenPaused onlyAdmin { require(_oracle != address(0), "Cannot be zero address"); oracleLatestRoundId = 0; oracle = AggregatorV3Interface(_oracle); // Dummy check to make sure the interface implements this function properly oracle.latestRoundData(); emit NewOracle(_oracle); } /** * @notice Set oracle update allowance * @dev Callable by admin */ function setOracleUpdateAllowance(uint256 _oracleUpdateAllowance) external whenPaused onlyAdmin { oracleUpdateAllowance = _oracleUpdateAllowance; emit NewOracleUpdateAllowance(_oracleUpdateAllowance); } /** * @notice Set treasury fee * @dev Callable by admin * fees are distributed 1% for Feature Maintenance 1% for development on distribution 1% for staff on distribution */ function setTreasuryFee(uint256 _treasuryFee) external whenPaused onlyAdmin { require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high"); treasuryFee = _treasuryFee; emit NewTreasuryFee(currentEpoch, treasuryFee); } /** * @notice It allows the owner to recover tokens sent to the contract by mistake * @param _token: token address * @param _amount: token amount * @dev Callable by owner */ function recoverToken(address _token, uint256 _amount) external onlyOwner { IERC20(_token).safeTransfer(address(msg.sender), _amount); emit TokenRecovery(_token, _amount); } /** * @notice Set admin address * @dev Callable by owner */ function setAdmin(address _adminAddress) external onlyOwner { require(_adminAddress != address(0), "Cannot be zero address"); adminAddress = _adminAddress; emit NewAdminAddress(_adminAddress); } /** * @notice Returns round epochs and bet information for a user that has participated * @param user: user address * @param cursor: cursor * @param size: size */ function getUserRounds( address user, uint256 cursor, uint256 size ) external view returns ( uint256[] memory, BetInfo[] memory, uint256 ) { uint256 length = size; if (length > userRounds[user].length - cursor) { length = userRounds[user].length - cursor; } uint256[] memory values = new uint256[](length); BetInfo[] memory betInfo = new BetInfo[](length); for (uint256 i = 0; i < length; i++) { values[i] = userRounds[user][cursor + i]; betInfo[i] = ledger[values[i]][user]; } return (values, betInfo, cursor + length); } /** * @notice Returns round epochs length * @param user: user address */ function getUserRoundsLength(address user) external view returns (uint256) { return userRounds[user].length; } function getJackpotAmount() external view returns (uint256) { return jackpotAcmAmt; } function getJackpotLockBlock() external view returns (uint256) { return jackpotLock; } /** * @notice Get the claimable stats of specific epoch and user account * @param epoch: epoch * @param user: user address */ function claimable(uint256 epoch, address user) public view returns (bool) { BetInfo memory betInfo = ledger[epoch][user]; Round memory round = rounds[epoch]; if (round.lockPrice == round.closePrice) { return false; } return round.oracleCalled && betInfo.amount != 0 && !betInfo.claimed && ((round.closePrice > round.lockPrice && betInfo.position == Position.Bull) || (round.closePrice < round.lockPrice && betInfo.position == Position.Bear)); } /** * @notice Get the refundable stats of specific epoch and user account * @param epoch: epoch * @param user: user address */ function refundable(uint256 epoch, address user) public view returns (bool) { BetInfo memory betInfo = ledger[epoch][user]; Round memory round = rounds[epoch]; return !round.oracleCalled && !betInfo.claimed && block.timestamp > round.closeTimestamp + bufferSeconds && betInfo.amount != 0; } /** * @notice Calculate rewards for round * @param epoch: epoch */ function _calculateRewards(uint256 epoch) internal { require(rounds[epoch].rewardBaseCalAmount == 0 && rounds[epoch].rewardAmount == 0, "Rewards calculated"); Round storage round = rounds[epoch]; uint256 rewardBaseCalAmount; uint256 treasuryAmt; uint256 rewardAmount; // Bull wins if (round.closePrice > round.lockPrice) { rewardBaseCalAmount = round.bullAmount; treasuryAmt = (round.totalAmount * treasuryFee) / 10000; rewardAmount = round.totalAmount - treasuryAmt; } // Bear wins else if (round.closePrice < round.lockPrice) { rewardBaseCalAmount = round.bearAmount; treasuryAmt = (round.totalAmount * treasuryFee) / 10000; rewardAmount = round.totalAmount - treasuryAmt; } // House wins else { rewardBaseCalAmount = 0; rewardAmount = 0; treasuryAmt = round.totalAmount; } round.rewardBaseCalAmount = rewardBaseCalAmount; round.rewardAmount = rewardAmount; // Add to treasury treasuryAmount += treasuryAmt; emit RewardsCalculated(epoch, rewardBaseCalAmount, rewardAmount, treasuryAmt); } /** * @notice End round * @param epoch: epoch * @param roundId: roundId * @param price: price of the round */ function _safeEndRound( uint256 epoch, uint256 roundId, int256 price ) internal { require(rounds[epoch].lockTimestamp != 0, "Can only end round after round has locked"); require(block.timestamp >= rounds[epoch].closeTimestamp, "Can only end round after closeTimestamp"); require( block.timestamp <= rounds[epoch].closeTimestamp + bufferSeconds, "Can only end round within bufferSeconds" ); Round storage round = rounds[epoch]; round.closePrice = price; round.closeOracleId = roundId; round.oracleCalled = true; emit EndRound(epoch, roundId, round.closePrice); } /** * @notice Lock round * @param epoch: epoch * @param roundId: roundId * @param price: price of the round */ function _safeLockRound( uint256 epoch, uint256 roundId, int256 price ) internal { require(rounds[epoch].startTimestamp != 0, "Can only lock round after round has started"); require(block.timestamp >= rounds[epoch].lockTimestamp, "Can only lock round after lockTimestamp"); require( block.timestamp <= rounds[epoch].lockTimestamp + bufferSeconds, "Can only lock round within bufferSeconds" ); Round storage round = rounds[epoch]; round.closeTimestamp = block.timestamp + intervalSeconds; round.lockPrice = price; round.lockOracleId = roundId; emit LockRound(epoch, roundId, round.lockPrice); } /** * @notice Start round * Previous round n-2 must end * @param epoch: epoch */ function _safeStartRound(uint256 epoch) internal { require(genesisStartOnce, "Can only run after genesisStartRound is triggered"); require(rounds[epoch - 2].closeTimestamp != 0, "Can only start round after round n-2 has ended"); require( block.timestamp >= rounds[epoch - 2].closeTimestamp, "Can only start new round after round n-2 closeTimestamp" ); _startRound(epoch); } /** * @notice Transfer BNB in a safe way * @param to: address to transfer BNB to * @param value: BNB amount to transfer (in wei) */ function _safeTransferBNB(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(""); require(success, "TransferHelper: BNB_TRANSFER_FAILED"); } /** * @notice Start round * Previous round n-2 must end * @param epoch: epoch */ function _startRound(uint256 epoch) internal { Round storage round = rounds[epoch]; round.startTimestamp = block.timestamp; round.lockTimestamp = block.timestamp + intervalSeconds; round.closeTimestamp = block.timestamp + (2 * intervalSeconds); round.epoch = epoch; round.totalAmount = 0; emit StartRound(epoch); } /** * @notice Determine if a round is valid for receiving bets * Round must have started and locked * Current timestamp must be within startTimestamp and closeTimestamp */ function _bettable(uint256 epoch) internal view returns (bool) { return rounds[epoch].startTimestamp != 0 && rounds[epoch].lockTimestamp != 0 && block.timestamp > rounds[epoch].startTimestamp && block.timestamp < rounds[epoch].lockTimestamp; } /** * @notice Get latest recorded price from oracle * If it falls below allowed buffer or has not updated, it would be invalid. */ function _getPriceFromOracle() internal view returns (uint80, int256) { uint256 leastAllowedTimestamp = block.timestamp + oracleUpdateAllowance; (uint80 roundId, int256 price, , uint256 timestamp, ) = oracle.latestRoundData(); require(timestamp <= leastAllowedTimestamp, "Oracle update exceeded max timestamp allowance"); require( uint256(roundId) > oracleLatestRoundId, "Oracle update roundId must be larger than oracleLatestRoundId" ); return (roundId, price); } /** * @notice Returns true if `account` is a contract. * @param account: account address */ function _isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } // Update the zai referral contract address by the owner function setzaiReferral(IZaiReferral _zaiReferral) public onlyOwner { zaiReferral = _zaiReferral; } // Update how many blocks to pay the jackpot function setPassedBlocks(uint256 _passedBlocks) public onlyOwner { passedBlocks = _passedBlocks; } // Update referral commission rate by the owner function setReferralCommissionRate(uint16 _referralCommissionRate) public onlyOperator { referralCommissionRate = _referralCommissionRate; } // Pay referral commission to the referrer who referred this user. function payReferralCommission(address _user, uint256 _pending) internal { if (address(zaiReferral) != address(0) && referralCommissionRate > 0) { address referrer = zaiReferral.getReferrer(_user); uint256 commissionAmount = _pending.mul(referralCommissionRate).div(10000); if (referrer != address(0) && commissionAmount > 0) { IERC20(zaif).safeTransfer(referrer, commissionAmount); uint256 TaxAmount = commissionAmount.mul(TaxFee).div(10000); commissionAmount = commissionAmount - TaxAmount; zaiReferral.recordReferralCommission(referrer, commissionAmount); emit ReferralCommissionPaid(_user, referrer, commissionAmount); } else{ // add to JackPot Amount > acumulation to pay in 200480 blocks roughly 1 week if(jackpotLock == 0){ jackpotLock = block.number; } jackpotAcmAmt += commissionAmount; // Amount in case jackpot round fails ,it backs to the jackpot jackpotAcmSafeCheck += commissionAmount; } } } }
1% total > 33.3% of 3%
uint256 staffAmt = (currentTreasuryAmount * 3333) / 10000;
6,385,314
[ 1, 21, 9, 2078, 405, 13159, 18, 23, 9, 434, 890, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 28904, 31787, 273, 261, 2972, 56, 266, 345, 22498, 6275, 380, 890, 3707, 23, 13, 342, 12619, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract HFVToken is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "HFV"; symbol = "HFV"; decimals = 18; _totalSupply = 700000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "HFV"; symbol = "HFV"; decimals = 18; _totalSupply = 700000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
14,715,613
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 44, 28324, 14432, 203, 3639, 3273, 273, 315, 44, 28324, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2371, 12648, 12648, 2787, 9449, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2021 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IController } from "../../interfaces/IController.sol"; import { IIndexExchangeAdapter } from "../../interfaces/IIndexExchangeAdapter.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IWETH } from "../../interfaces/external/IWETH.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { Position } from "../lib/Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { Uint256ArrayUtils } from "../../lib/Uint256ArrayUtils.sol"; /** * @title GeneralIndexModule * @author Set Protocol * * Smart contract that facilitates rebalances for indices. Manager can update allocation by calling startRebalance(). * There is no "end" to a rebalance, however once there are no more tokens to sell the rebalance is effectively over * until the manager calls startRebalance() again with a new allocation. Once a new allocation is passed in, allowed * traders can submit rebalance transactions by calling trade() and specifying the component they wish to rebalance. * All parameterizations for a trade are set by the manager ahead of time, including max trade size, coolOffPeriod bet- * ween trades, and exchange to trade on. WETH is used as the quote asset for all trades, near the end of rebalance * tradeRemaingingWETH() or raiseAssetTargets() can be called to clean up any excess WETH positions. Once a component's * target allocation is met any further attempted trades of that component will revert. * * SECURITY ASSUMPTION: * - Works with following modules: StreamingFeeModule, BasicIssuanceModule (any other module additions to Sets using * this module need to be examined separately) */ contract GeneralIndexModule is ModuleBase, ReentrancyGuard { using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using Position for uint256; using Math for uint256; using Position for ISetToken; using Invoke for ISetToken; using AddressArrayUtils for address[]; using AddressArrayUtils for IERC20[]; using Uint256ArrayUtils for uint256[]; /* ============ Struct ============ */ struct TradeExecutionParams { uint256 targetUnit; // Target unit of component for Set uint256 maxSize; // Max trade size in precise units uint256 coolOffPeriod; // Required time between trades for the asset uint256 lastTradeTimestamp; // Timestamp of last trade string exchangeName; // Name of exchange adapter bytes exchangeData; // Arbitrary data that can be used to encode exchange specific settings (fee tier) or features (multi-hop) } struct TradePermissionInfo { bool anyoneTrade; // Boolean indicating if anyone can execute a trade address[] tradersHistory; // Tracks permissioned traders to be deleted on module removal mapping(address => bool) tradeAllowList; // Mapping indicating which addresses are allowed to execute trade } struct RebalanceInfo { uint256 positionMultiplier; // Position multiplier at the beginning of rebalance uint256 raiseTargetPercentage; // Amount to raise all unit targets by if allowed (in precise units) address[] rebalanceComponents; // Array of components involved in rebalance } struct TradeInfo { ISetToken setToken; // Instance of SetToken IIndexExchangeAdapter exchangeAdapter; // Instance of Exchange Adapter address sendToken; // Address of token being sold address receiveToken; // Address of token being bought bool isSendTokenFixed; // Boolean indicating fixed asset is send token uint256 setTotalSupply; // Total supply of Set (in precise units) uint256 totalFixedQuantity; // Total quantity of fixed asset being traded uint256 sendQuantity; // Units of component sent to the exchange uint256 floatingQuantityLimit; // Max/min amount of floating token spent/received during trade uint256 preTradeSendTokenBalance; // Total initial balance of token being sold uint256 preTradeReceiveTokenBalance; // Total initial balance of token being bought bytes exchangeData; // Arbitrary data for executing trade on given exchange } /* ============ Events ============ */ event TradeMaximumUpdated(ISetToken indexed _setToken, address indexed _component, uint256 _newMaximum); event AssetExchangeUpdated(ISetToken indexed _setToken, address indexed _component, string _newExchangeName); event CoolOffPeriodUpdated(ISetToken indexed _setToken, address indexed _component, uint256 _newCoolOffPeriod); event ExchangeDataUpdated(ISetToken indexed _setToken, address indexed _component, bytes _newExchangeData); event RaiseTargetPercentageUpdated(ISetToken indexed _setToken, uint256 indexed _raiseTargetPercentage); event AssetTargetsRaised(ISetToken indexed _setToken, uint256 indexed positionMultiplier); event AnyoneTradeUpdated(ISetToken indexed _setToken, bool indexed _status); event TraderStatusUpdated(ISetToken indexed _setToken, address indexed _trader, bool _status); event TradeExecuted( ISetToken indexed _setToken, address indexed _sellComponent, address indexed _buyComponent, IIndexExchangeAdapter _exchangeAdapter, address _executor, uint256 _netAmountSold, uint256 _netAmountReceived, uint256 _protocolFee ); event RebalanceStarted( ISetToken indexed _setToken, address[] aggregateComponents, uint256[] aggregateTargetUnits, uint256 indexed positionMultiplier ); /* ============ Constants ============ */ uint256 private constant GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX = 0; // Id of protocol fee % assigned to this module in the Controller /* ============ State Variables ============ */ mapping(ISetToken => mapping(IERC20 => TradeExecutionParams)) public executionInfo; // Mapping of SetToken to execution parameters of each asset on SetToken mapping(ISetToken => TradePermissionInfo) public permissionInfo; // Mapping of SetToken to trading permissions mapping(ISetToken => RebalanceInfo) public rebalanceInfo; // Mapping of SetToken to relevant data for current rebalance IWETH public immutable weth; // Weth contract address /* ============ Modifiers ============ */ modifier onlyAllowedTrader(ISetToken _setToken) { _validateOnlyAllowedTrader(_setToken); _; } modifier onlyEOAIfUnrestricted(ISetToken _setToken) { _validateOnlyEOAIfUnrestricted(_setToken); _; } /* ============ Constructor ============ */ constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) { weth = _weth; } /* ============ External Functions ============ */ /** * MANAGER ONLY: Changes the target allocation of the Set, opening it up for trading by the Sets designated traders. The manager * must pass in any new components and their target units (units defined by the amount of that component the manager wants in 10**18 * units of a SetToken). Old component target units must be passed in, in the current order of the components array on the * SetToken. If a component is being removed it's index in the _oldComponentsTargetUnits should be set to 0. Additionally, the * positionMultiplier is passed in, in order to adjust the target units in the event fees are accrued or some other activity occurs * that changes the positionMultiplier of the Set. This guarantees the same relative allocation between all the components. * * @param _setToken Address of the SetToken to be rebalanced * @param _newComponents Array of new components to add to allocation * @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array * @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of * _setToken.getComponents() array, if component being removed set to 0. * @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units * if fees accrued */ function startRebalance( ISetToken _setToken, address[] calldata _newComponents, uint256[] calldata _newComponentsTargetUnits, uint256[] calldata _oldComponentsTargetUnits, uint256 _positionMultiplier ) external onlyManagerAndValidSet(_setToken) { ( address[] memory aggregateComponents, uint256[] memory aggregateTargetUnits ) = _getAggregateComponentsAndUnits( _setToken.getComponents(), _newComponents, _newComponentsTargetUnits, _oldComponentsTargetUnits ); for (uint256 i = 0; i < aggregateComponents.length; i++) { require(!_setToken.hasExternalPosition(aggregateComponents[i]), "External positions not allowed"); executionInfo[_setToken][IERC20(aggregateComponents[i])].targetUnit = aggregateTargetUnits[i]; } rebalanceInfo[_setToken].rebalanceComponents = aggregateComponents; rebalanceInfo[_setToken].positionMultiplier = _positionMultiplier; emit RebalanceStarted(_setToken, aggregateComponents, aggregateTargetUnits, _positionMultiplier); } /** * ACCESS LIMITED: Calling trade() pushes the current component units closer to the target units defined by the manager in startRebalance(). * Only approved addresses can call, if anyoneTrade is false then contracts are allowed to call otherwise calling address must be EOA. * * Trade can be called at anytime but will revert if the passed component's target unit is met or cool off period hasn't passed. Trader can pass * in a max/min amount of ETH spent/received in the trade based on if the component is being bought/sold in order to prevent sandwich attacks. * The parameters defined by the manager are used to determine which exchange will be used and the size of the trade. Trade size will default * to max trade size unless the max trade size would exceed the target, then an amount that would match the target unit is traded. Protocol fees, * if enabled, are collected in the token received in a trade. * * @param _setToken Address of the SetToken * @param _component Address of SetToken component to trade * @param _ethQuantityLimit Max/min amount of ETH spent/received during trade */ function trade( ISetToken _setToken, IERC20 _component, uint256 _ethQuantityLimit ) external nonReentrant onlyAllowedTrader(_setToken) onlyEOAIfUnrestricted(_setToken) virtual { _validateTradeParameters(_setToken, _component); TradeInfo memory tradeInfo = _createTradeInfo(_setToken, _component, _ethQuantityLimit); _executeTrade(tradeInfo); uint256 protocolFee = _accrueProtocolFee(tradeInfo); (uint256 netSendAmount, uint256 netReceiveAmount) = _updatePositionStateAndTimestamp(tradeInfo, _component); emit TradeExecuted( tradeInfo.setToken, tradeInfo.sendToken, tradeInfo.receiveToken, tradeInfo.exchangeAdapter, msg.sender, netSendAmount, netReceiveAmount, protocolFee ); } /** * ACCESS LIMITED: Only callable when 1) there are no more components to be sold and, 2) entire remaining WETH amount (above WETH target) can be * traded such that resulting inflows won't exceed component's maxTradeSize nor overshoot the target unit. To be used near the end of rebalances * when a component's calculated trade size is greater in value than remaining WETH. * * Only approved addresses can call, if anyoneTrade is false then contracts are allowed to call otherwise calling address must be EOA. Trade * can be called at anytime but will revert if the passed component's target unit is met or cool off period hasn't passed. Like with trade() * a minimum component receive amount can be set. * * @param _setToken Address of the SetToken * @param _component Address of the SetToken component to trade * @param _minComponentReceived Min amount of component received during trade */ function tradeRemainingWETH( ISetToken _setToken, IERC20 _component, uint256 _minComponentReceived ) external nonReentrant onlyAllowedTrader(_setToken) onlyEOAIfUnrestricted(_setToken) virtual { require(_noTokensToSell(_setToken), "Sell other set components first"); require( executionInfo[_setToken][weth].targetUnit < _getDefaultPositionRealUnit(_setToken, weth), "WETH is below target unit" ); _validateTradeParameters(_setToken, _component); TradeInfo memory tradeInfo = _createTradeRemainingInfo(_setToken, _component, _minComponentReceived); _executeTrade(tradeInfo); uint256 protocolFee = _accrueProtocolFee(tradeInfo); (uint256 netSendAmount, uint256 netReceiveAmount) = _updatePositionStateAndTimestamp(tradeInfo, _component); require( netReceiveAmount.add(protocolFee) < executionInfo[_setToken][_component].maxSize, "Trade amount > max trade size" ); _validateComponentPositionUnit(_setToken, _component); emit TradeExecuted( tradeInfo.setToken, tradeInfo.sendToken, tradeInfo.receiveToken, tradeInfo.exchangeAdapter, msg.sender, netSendAmount, netReceiveAmount, protocolFee ); } /** * ACCESS LIMITED: For situation where all target units met and remaining WETH, uniformly raise targets by same percentage by applying * to logged positionMultiplier in RebalanceInfo struct, in order to allow further trading. Can be called multiple times if necessary, * targets are increased by amount specified by raiseAssetTargetsPercentage as set by manager. In order to reduce tracking error * raising the target by a smaller amount allows greater granularity in finding an equilibrium between the excess ETH and components * that need to be bought. Raising the targets too much could result in vastly under allocating to WETH as more WETH than necessary is * spent buying the components to meet their new target. * * @param _setToken Address of the SetToken */ function raiseAssetTargets(ISetToken _setToken) external onlyAllowedTrader(_setToken) virtual { require( _allTargetsMet(_setToken) && _getDefaultPositionRealUnit(_setToken, weth) > _getNormalizedTargetUnit(_setToken, weth), "Targets not met or ETH =~ 0" ); // positionMultiplier / (10^18 + raiseTargetPercentage) // ex: (10 ** 18) / ((10 ** 18) + ether(.0025)) => 997506234413965087 rebalanceInfo[_setToken].positionMultiplier = rebalanceInfo[_setToken].positionMultiplier.preciseDiv( PreciseUnitMath.preciseUnit().add(rebalanceInfo[_setToken].raiseTargetPercentage) ); emit AssetTargetsRaised(_setToken, rebalanceInfo[_setToken].positionMultiplier); } /** * MANAGER ONLY: Set trade maximums for passed components of the SetToken. Can be called at anytime. * Note: Trade maximums must be set before rebalance can begin properly - they are zero by * default and trades will not execute if a component's trade size is greater than the maximum. * * @param _setToken Address of the SetToken * @param _components Array of components * @param _tradeMaximums Array of trade maximums mapping to correct component */ function setTradeMaximums( ISetToken _setToken, address[] memory _components, uint256[] memory _tradeMaximums ) external onlyManagerAndValidSet(_setToken) { _components.validatePairsWithArray(_tradeMaximums); for (uint256 i = 0; i < _components.length; i++) { executionInfo[_setToken][IERC20(_components[i])].maxSize = _tradeMaximums[i]; emit TradeMaximumUpdated(_setToken, _components[i], _tradeMaximums[i]); } } /** * MANAGER ONLY: Set exchange for passed components of the SetToken. Can be called at anytime. * * @param _setToken Address of the SetToken * @param _components Array of components * @param _exchangeNames Array of exchange names mapping to correct component */ function setExchanges( ISetToken _setToken, address[] memory _components, string[] memory _exchangeNames ) external onlyManagerAndValidSet(_setToken) { _components.validatePairsWithArray(_exchangeNames); for (uint256 i = 0; i < _components.length; i++) { if (_components[i] != address(weth)) { require( controller.getIntegrationRegistry().isValidIntegration(address(this), _exchangeNames[i]), "Unrecognized exchange name" ); executionInfo[_setToken][IERC20(_components[i])].exchangeName = _exchangeNames[i]; emit AssetExchangeUpdated(_setToken, _components[i], _exchangeNames[i]); } } } /** * MANAGER ONLY: Set cool off periods for passed components of the SetToken. Can be called at any time. * * @param _setToken Address of the SetToken * @param _components Array of components * @param _coolOffPeriods Array of cool off periods to correct component */ function setCoolOffPeriods( ISetToken _setToken, address[] memory _components, uint256[] memory _coolOffPeriods ) external onlyManagerAndValidSet(_setToken) { _components.validatePairsWithArray(_coolOffPeriods); for (uint256 i = 0; i < _components.length; i++) { executionInfo[_setToken][IERC20(_components[i])].coolOffPeriod = _coolOffPeriods[i]; emit CoolOffPeriodUpdated(_setToken, _components[i], _coolOffPeriods[i]); } } /** * MANAGER ONLY: Set arbitrary byte data on a per asset basis that can be used to pass exchange specific settings (i.e. specifying * fee tiers) or exchange specific features (enabling multi-hop trades). Can be called at any time. * * @param _setToken Address of the SetToken * @param _components Array of components * @param _exchangeData Array of exchange specific arbitrary bytes data */ function setExchangeData( ISetToken _setToken, address[] memory _components, bytes[] memory _exchangeData ) external onlyManagerAndValidSet(_setToken) { _components.validatePairsWithArray(_exchangeData); for (uint256 i = 0; i < _components.length; i++) { executionInfo[_setToken][IERC20(_components[i])].exchangeData = _exchangeData[i]; emit ExchangeDataUpdated(_setToken, _components[i], _exchangeData[i]); } } /** * MANAGER ONLY: Set amount by which all component's targets units would be raised. Can be called at any time. * * @param _setToken Address of the SetToken * @param _raiseTargetPercentage Amount to raise all component's unit targets by (in precise units) */ function setRaiseTargetPercentage( ISetToken _setToken, uint256 _raiseTargetPercentage ) external onlyManagerAndValidSet(_setToken) { require(_raiseTargetPercentage > 0, "Target percentage must be > 0"); rebalanceInfo[_setToken].raiseTargetPercentage = _raiseTargetPercentage; emit RaiseTargetPercentageUpdated(_setToken, _raiseTargetPercentage); } /** * MANAGER ONLY: Toggles ability for passed addresses to call trade() or tradeRemainingWETH(). Can be called at any time. * * @param _setToken Address of the SetToken * @param _traders Array trader addresses to toggle status * @param _statuses Booleans indicating if matching trader can trade */ function setTraderStatus( ISetToken _setToken, address[] memory _traders, bool[] memory _statuses ) external onlyManagerAndValidSet(_setToken) { _traders.validatePairsWithArray(_statuses); for (uint256 i = 0; i < _traders.length; i++) { _updateTradersHistory(_setToken, _traders[i], _statuses[i]); permissionInfo[_setToken].tradeAllowList[_traders[i]] = _statuses[i]; emit TraderStatusUpdated(_setToken, _traders[i], _statuses[i]); } } /** * MANAGER ONLY: Toggle whether anyone can trade, if true bypasses the traderAllowList. Can be called at anytime. * * @param _setToken Address of the SetToken * @param _status Boolean indicating if anyone can trade */ function setAnyoneTrade(ISetToken _setToken, bool _status) external onlyManagerAndValidSet(_setToken) { permissionInfo[_setToken].anyoneTrade = _status; emit AnyoneTradeUpdated(_setToken, _status); } /** * MANAGER ONLY: Called to initialize module to SetToken in order to allow GeneralIndexModule access for rebalances. * Grabs the current units for each asset in the Set and set's the targetUnit to that unit in order to prevent any * trading until startRebalance() is explicitly called. Position multiplier is also logged in order to make sure any * position multiplier changes don't unintentionally open the Set for rebalancing. * * @param _setToken Address of the Set Token */ function initialize(ISetToken _setToken) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { ISetToken.Position[] memory positions = _setToken.getPositions(); for (uint256 i = 0; i < positions.length; i++) { ISetToken.Position memory position = positions[i]; require(position.positionState == 0, "External positions not allowed"); executionInfo[_setToken][IERC20(position.component)].targetUnit = position.unit.toUint256(); executionInfo[_setToken][IERC20(position.component)].lastTradeTimestamp = 0; } rebalanceInfo[_setToken].positionMultiplier = _setToken.positionMultiplier().toUint256(); _setToken.initializeModule(); } /** * Called by a SetToken to notify that this module was removed from the SetToken. * Clears the rebalanceInfo and permissionsInfo of the calling SetToken. * IMPORTANT: SetToken's execution settings, including trade maximums and exchange names, * are NOT DELETED. Restoring a previously removed module requires that care is taken to * initialize execution settings appropriately. */ function removeModule() external override { TradePermissionInfo storage tokenPermissionInfo = permissionInfo[ISetToken(msg.sender)]; for (uint i = 0; i < tokenPermissionInfo.tradersHistory.length; i++) { tokenPermissionInfo.tradeAllowList[tokenPermissionInfo.tradersHistory[i]] = false; } delete rebalanceInfo[ISetToken(msg.sender)]; delete permissionInfo[ISetToken(msg.sender)]; } /* ============ External View Functions ============ */ /** * Get the array of SetToken components involved in rebalance. * * @param _setToken Address of the SetToken * * @return address[] Array of _setToken components involved in rebalance */ function getRebalanceComponents(ISetToken _setToken) external view onlyValidAndInitializedSet(_setToken) returns (address[] memory) { return rebalanceInfo[_setToken].rebalanceComponents; } /** * Calculates the amount of a component that is going to be traded and whether the component is being bought * or sold. If currentUnit and targetUnit are the same, function will revert. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * * @return isSendTokenFixed Boolean indicating fixed asset is send token * @return componentQuantity Amount of component being traded */ function getComponentTradeQuantityAndDirection( ISetToken _setToken, IERC20 _component ) external view onlyValidAndInitializedSet(_setToken) returns (bool, uint256) { require( rebalanceInfo[_setToken].rebalanceComponents.contains(address(_component)), "Component not recognized" ); uint256 totalSupply = _setToken.totalSupply(); return _calculateTradeSizeAndDirection(_setToken, _component, totalSupply); } /** * Get if a given address is an allowed trader. * * @param _setToken Address of the SetToken * @param _trader Address of the trader * * @return bool True if _trader is allowed to trade, else false */ function getIsAllowedTrader(ISetToken _setToken, address _trader) external view onlyValidAndInitializedSet(_setToken) returns (bool) { return _isAllowedTrader(_setToken, _trader); } /** * Get the list of traders who are allowed to call trade(), tradeRemainingWeth(), and raiseAssetTarget() * * @param _setToken Address of the SetToken * * @return address[] */ function getAllowedTraders(ISetToken _setToken) external view onlyValidAndInitializedSet(_setToken) returns (address[] memory) { return permissionInfo[_setToken].tradersHistory; } /* ============ Internal Functions ============ */ /** * A rebalance is a multi-step process in which current Set components are sold for a * bridge asset (WETH) before buying target components in the correct amount to achieve * the desired balance between elements in the set. * * Step 1 | Step 2 * ------------------------------------------- * Component --> WETH | WETH --> Component * ------------------------------------------- * * The syntax we use frames this as trading from a "fixed" amount of one component to a * "fixed" amount of another via a "floating limit" which is *either* the maximum size of * the trade we want to make (trades may be tranched to avoid moving markets) OR the minimum * amount of tokens we expect to receive. The different meanings of the floating limit map to * the trade sequence as below: * * Step 1: Component --> WETH * ---------------------------------------------------------- * | Fixed | Floating limit | * ---------------------------------------------------------- * send (Component) | YES | | * recieve (WETH) | | Min WETH to receive | * ---------------------------------------------------------- * * Step 2: WETH --> Component * ---------------------------------------------------------- * | Fixed | Floating limit | * ---------------------------------------------------------- * send (WETH) | NO | Max WETH to send | * recieve (Component) | YES | | * ---------------------------------------------------------- * * Additionally, there is an edge case where price volatility during a rebalance * results in remaining WETH which needs to be allocated proportionately. In this case * the values are as below: * * Edge case: Remaining WETH --> Component * ---------------------------------------------------------- * | Fixed | Floating limit | * ---------------------------------------------------------- * send (WETH) | YES | | * recieve (Component) | | Min component to receive | * ---------------------------------------------------------- */ /** * Create and return TradeInfo struct. This function reverts if the target has already been met. * If this is a trade from component into WETH, sell the total fixed component quantity * and expect to receive an ETH amount the user has specified (or more). If it's a trade from * WETH into a component, sell the lesser of: the user's WETH limit OR the SetToken's * remaining WETH balance and expect to receive a fixed component quantity. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * @param _ethQuantityLimit Max/min amount of weth spent/received during trade * * @return tradeInfo Struct containing data for trade */ function _createTradeInfo( ISetToken _setToken, IERC20 _component, uint256 _ethQuantityLimit ) internal view virtual returns (TradeInfo memory tradeInfo) { tradeInfo = _getDefaultTradeInfo(_setToken, _component, true); if (tradeInfo.isSendTokenFixed){ tradeInfo.sendQuantity = tradeInfo.totalFixedQuantity; tradeInfo.floatingQuantityLimit = _ethQuantityLimit; } else { tradeInfo.sendQuantity = _ethQuantityLimit.min(tradeInfo.preTradeSendTokenBalance); tradeInfo.floatingQuantityLimit = tradeInfo.totalFixedQuantity; } } /** * Create and return TradeInfo struct. This function does NOT check if the WETH target has been met. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * @param _minComponentReceived Min amount of component received during trade * * @return tradeInfo Struct containing data for tradeRemaining info */ function _createTradeRemainingInfo( ISetToken _setToken, IERC20 _component, uint256 _minComponentReceived ) internal view returns (TradeInfo memory tradeInfo) { tradeInfo = _getDefaultTradeInfo(_setToken, _component, false); (,, uint256 currentNotional, uint256 targetNotional ) = _getUnitsAndNotionalAmounts(_setToken, weth, tradeInfo.setTotalSupply); tradeInfo.sendQuantity = currentNotional.sub(targetNotional); tradeInfo.floatingQuantityLimit = _minComponentReceived; tradeInfo.isSendTokenFixed = true; } /** * Create and returns a partial TradeInfo struct with all fields that overlap between `trade` * and `tradeRemaining` info constructors filled in. Values for `sendQuantity` and `floatingQuantityLimit` * are derived separately, outside this method. `trade` requires that trade size and direction are * calculated, whereas `tradeRemaining` automatically sets WETH as the sendToken and _component * as receiveToken. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * @param calculateTradeDirection Indicates whether method should calculate trade size and direction * * @return tradeInfo Struct containing partial data for trade */ function _getDefaultTradeInfo(ISetToken _setToken, IERC20 _component, bool calculateTradeDirection) internal view returns (TradeInfo memory tradeInfo) { tradeInfo.setToken = _setToken; tradeInfo.setTotalSupply = _setToken.totalSupply(); tradeInfo.exchangeAdapter = _getExchangeAdapter(_setToken, _component); tradeInfo.exchangeData = executionInfo[_setToken][_component].exchangeData; if(calculateTradeDirection){ ( tradeInfo.isSendTokenFixed, tradeInfo.totalFixedQuantity ) = _calculateTradeSizeAndDirection(_setToken, _component, tradeInfo.setTotalSupply); } if (tradeInfo.isSendTokenFixed){ tradeInfo.sendToken = address(_component); tradeInfo.receiveToken = address(weth); } else { tradeInfo.sendToken = address(weth); tradeInfo.receiveToken = address(_component); } tradeInfo.preTradeSendTokenBalance = IERC20(tradeInfo.sendToken).balanceOf(address(_setToken)); tradeInfo.preTradeReceiveTokenBalance = IERC20(tradeInfo.receiveToken).balanceOf(address(_setToken)); } /** * Function handles all interactions with exchange. All GeneralIndexModule adapters must allow for selling or buying a fixed * quantity of a token in return for a non-fixed (floating) quantity of a token. If `isSendTokenFixed` is true then the adapter * will choose the exchange interface associated with inputting a fixed amount, otherwise it will select the interface used for * receiving a fixed amount. Any other exchange specific data can also be created by calling generateDataParam function. * * @param _tradeInfo Struct containing trade information used in internal functions */ function _executeTrade(TradeInfo memory _tradeInfo) internal virtual { _tradeInfo.setToken.invokeApprove( _tradeInfo.sendToken, _tradeInfo.exchangeAdapter.getSpender(), _tradeInfo.sendQuantity ); ( address targetExchange, uint256 callValue, bytes memory methodData ) = _tradeInfo.exchangeAdapter.getTradeCalldata( _tradeInfo.sendToken, _tradeInfo.receiveToken, address(_tradeInfo.setToken), _tradeInfo.isSendTokenFixed, _tradeInfo.sendQuantity, _tradeInfo.floatingQuantityLimit, _tradeInfo.exchangeData ); _tradeInfo.setToken.invoke(targetExchange, callValue, methodData); } /** * Retrieve fee from controller and calculate total protocol fee and send from SetToken to protocol recipient. * The protocol fee is collected from the amount of received token in the trade. * * @param _tradeInfo Struct containing trade information used in internal functions * * @return protocolFee Amount of receive token taken as protocol fee */ function _accrueProtocolFee(TradeInfo memory _tradeInfo) internal returns (uint256 protocolFee) { uint256 exchangedQuantity = IERC20(_tradeInfo.receiveToken) .balanceOf(address(_tradeInfo.setToken)) .sub(_tradeInfo.preTradeReceiveTokenBalance); protocolFee = getModuleFee(GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX, exchangedQuantity); payProtocolFeeFromSetToken(_tradeInfo.setToken, _tradeInfo.receiveToken, protocolFee); } /** * Update SetToken positions and executionInfo's last trade timestamp. This function is intended * to be called after the fees have been accrued, hence it returns the amount of tokens bought net of fees. * * @param _tradeInfo Struct containing trade information used in internal functions * @param _component IERC20 component which was traded * * @return netSendAmount Amount of sendTokens used in the trade * @return netReceiveAmount Amount of receiveTokens received in the trade (net of fees) */ function _updatePositionStateAndTimestamp(TradeInfo memory _tradeInfo, IERC20 _component) internal returns (uint256 netSendAmount, uint256 netReceiveAmount) { (uint256 postTradeSendTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition( _tradeInfo.sendToken, _tradeInfo.setTotalSupply, _tradeInfo.preTradeSendTokenBalance ); (uint256 postTradeReceiveTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition( _tradeInfo.receiveToken, _tradeInfo.setTotalSupply, _tradeInfo.preTradeReceiveTokenBalance ); netSendAmount = _tradeInfo.preTradeSendTokenBalance.sub(postTradeSendTokenBalance); netReceiveAmount = postTradeReceiveTokenBalance.sub(_tradeInfo.preTradeReceiveTokenBalance); executionInfo[_tradeInfo.setToken][_component].lastTradeTimestamp = block.timestamp; } /** * Adds or removes newly permissioned trader to/from permissionsInfo traderHistory. It's * necessary to verify that traderHistory contains the address because AddressArrayUtils will * throw when attempting to remove a non-element and it's possible someone can set a new * trader's status to false. * * @param _setToken Instance of the SetToken * @param _trader Trader whose permission is being set * @param _status Boolean permission being set */ function _updateTradersHistory(ISetToken _setToken, address _trader, bool _status) internal { if (_status && !permissionInfo[_setToken].tradersHistory.contains(_trader)) { permissionInfo[_setToken].tradersHistory.push(_trader); } else if(!_status && permissionInfo[_setToken].tradersHistory.contains(_trader)) { permissionInfo[_setToken].tradersHistory.removeStorage(_trader); } } /** * Calculates the amount of a component is going to be traded and whether the component is being bought or sold. * If currentUnit and targetUnit are the same, function will revert. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * @param _totalSupply Total supply of _setToken * * @return isSendTokenFixed Boolean indicating fixed asset is send token * @return totalFixedQuantity Amount of fixed token to send or receive */ function _calculateTradeSizeAndDirection( ISetToken _setToken, IERC20 _component, uint256 _totalSupply ) internal view returns (bool isSendTokenFixed, uint256 totalFixedQuantity) { uint256 protocolFee = controller.getModuleFee(address(this), GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX); uint256 componentMaxSize = executionInfo[_setToken][_component].maxSize; ( uint256 currentUnit, uint256 targetUnit, uint256 currentNotional, uint256 targetNotional ) = _getUnitsAndNotionalAmounts(_setToken, _component, _totalSupply); require(currentUnit != targetUnit, "Target already met"); isSendTokenFixed = targetNotional < currentNotional; // In order to account for fees taken by protocol when buying the notional difference between currentUnit // and targetUnit is divided by (1 - protocolFee) to make sure that targetUnit can be met. Failure to // do so would lead to never being able to meet target of components that need to be bought. // // ? - lesserOf: (componentMaxSize, (currentNotional - targetNotional)) // : - lesserOf: (componentMaxSize, (targetNotional - currentNotional) / 10 ** 18 - protocolFee) totalFixedQuantity = isSendTokenFixed ? componentMaxSize.min(currentNotional.sub(targetNotional)) : componentMaxSize.min(targetNotional.sub(currentNotional).preciseDiv(PreciseUnitMath.preciseUnit().sub(protocolFee))); } /** * Check if all targets are met. * * @param _setToken Instance of the SetToken to be rebalanced * * @return bool True if all component's target units have been met, otherwise false */ function _allTargetsMet(ISetToken _setToken) internal view returns (bool) { address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents; for (uint256 i = 0; i < rebalanceComponents.length; i++) { if (_targetUnmet(_setToken, rebalanceComponents[i])) { return false; } } return true; } /** * Determine if passed address is allowed to call trade for the SetToken. If anyoneTrade set to true anyone can call otherwise * needs to be approved. * * @param _setToken Instance of SetToken to be rebalanced * @param _trader Address of the trader who called contract function * * @return bool True if trader is an approved trader for the SetToken */ function _isAllowedTrader(ISetToken _setToken, address _trader) internal view returns (bool) { TradePermissionInfo storage permissions = permissionInfo[_setToken]; return permissions.anyoneTrade || permissions.tradeAllowList[_trader]; } /** * Checks if sell conditions are met. The component cannot be WETH and its normalized target * unit must be less than its default position real unit * * @param _setToken Instance of the SetToken to be rebalanced * @param _component Component evaluated for sale * * @return bool True if sell allowed, false otherwise */ function _canSell(ISetToken _setToken, address _component) internal view returns(bool) { return ( _component != address(weth) && ( _getNormalizedTargetUnit(_setToken, IERC20(_component)) < _getDefaultPositionRealUnit(_setToken,IERC20(_component)) ) ); } /** * Check if there are any more tokens to sell. Since we allow WETH to float around it's target during rebalances it is not checked. * * @param _setToken Instance of the SetToken to be rebalanced * * @return bool True if there is not any component that can be sold, otherwise false */ function _noTokensToSell(ISetToken _setToken) internal view returns (bool) { address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents; for (uint256 i = 0; i < rebalanceComponents.length; i++) { if (_canSell(_setToken, rebalanceComponents[i]) ) { return false; } } return true; } /** * Determines if a target is met. Due to small rounding errors converting between virtual and * real unit on SetToken we allow for a 1 wei buffer when checking if target is met. In order to * avoid subtraction overflow errors targetUnits of zero check for an exact amount. WETH is not * checked as it is allowed to float around its target. * * @param _setToken Instance of the SetToken to be rebalanced * @param _component Component whose target is evaluated * * @return bool True if component's target units are met, false otherwise */ function _targetUnmet(ISetToken _setToken, address _component) internal view returns(bool) { if (_component == address(weth)) return false; uint256 normalizedTargetUnit = _getNormalizedTargetUnit(_setToken, IERC20(_component)); uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, IERC20(_component)); return (normalizedTargetUnit > 0) ? !(normalizedTargetUnit.approximatelyEquals(currentUnit, 1)) : normalizedTargetUnit != currentUnit; } /** * Validate component position unit has not exceeded it's target unit. This is used during tradeRemainingWETH() to make sure * the amount of component bought does not exceed the targetUnit. * * @param _setToken Instance of the SetToken * @param _component IERC20 component whose position units are to be validated */ function _validateComponentPositionUnit(ISetToken _setToken, IERC20 _component) internal view { uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component); uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component); require(currentUnit <= targetUnit, "Can not exceed target unit"); } /** * Validate that component is a valid component and enough time has elapsed since component's last trade. Traders * cannot explicitly trade WETH, it may only implicitly be traded by being the quote asset for other component trades. * * @param _setToken Instance of the SetToken * @param _component IERC20 component to be validated */ function _validateTradeParameters(ISetToken _setToken, IERC20 _component) internal view virtual { require(address(_component) != address(weth), "Can not explicitly trade WETH"); require( rebalanceInfo[_setToken].rebalanceComponents.contains(address(_component)), "Component not part of rebalance" ); TradeExecutionParams memory componentInfo = executionInfo[_setToken][_component]; require( componentInfo.lastTradeTimestamp.add(componentInfo.coolOffPeriod) <= block.timestamp, "Component cool off in progress" ); require(!_setToken.hasExternalPosition(address(_component)), "External positions not allowed"); } /** * Extends and/or updates the current component set and its target units with new components and targets, * Validates inputs, requiring that that new components and new target units arrays are the same size, and * that the number of old components target units matches the number of current components. Throws if * a duplicate component has been added. * * @param _currentComponents Complete set of current SetToken components * @param _newComponents Array of new components to add to allocation * @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array * @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of * _setToken.getComponents() array, if component being removed set to 0. * * @return aggregateComponents Array of current components extended by new components, without duplicates * @return aggregateTargetUnits Array of old component target units extended by new target units, without duplicates */ function _getAggregateComponentsAndUnits( address[] memory _currentComponents, address[] calldata _newComponents, uint256[] calldata _newComponentsTargetUnits, uint256[] calldata _oldComponentsTargetUnits ) internal pure returns (address[] memory aggregateComponents, uint256[] memory aggregateTargetUnits) { // Don't use validate arrays because empty arrays are valid require(_newComponents.length == _newComponentsTargetUnits.length, "Array length mismatch"); require(_currentComponents.length == _oldComponentsTargetUnits.length, "Old Components targets missing"); aggregateComponents = _currentComponents.extend(_newComponents); aggregateTargetUnits = _oldComponentsTargetUnits.extend(_newComponentsTargetUnits); require(!aggregateComponents.hasDuplicate(), "Cannot duplicate components"); } /** * Get the SetToken's default position as uint256 * * @param _setToken Instance of the SetToken * @param _component IERC20 component to fetch the default position for * * return uint256 Real unit position */ function _getDefaultPositionRealUnit(ISetToken _setToken, IERC20 _component) internal view returns (uint256) { return _setToken.getDefaultPositionRealUnit(address(_component)).toUint256(); } /** * Gets exchange adapter address for a component after checking that it exists in the * IntegrationRegistry. This method is called during a trade and must validate the adapter * because its state may have changed since it was set in a separate transaction. * * @param _setToken Instance of the SetToken to be rebalanced * @param _component IERC20 component whose exchange adapter is fetched * * @return IExchangeAdapter Adapter address */ function _getExchangeAdapter(ISetToken _setToken, IERC20 _component) internal view returns(IIndexExchangeAdapter) { return IIndexExchangeAdapter(getAndValidateAdapter(executionInfo[_setToken][_component].exchangeName)); } /** * Calculates and returns the normalized target unit value. * * @param _setToken Instance of the SetToken to be rebalanced * @param _component IERC20 component whose normalized target unit is required * * @return uint256 Normalized target unit of the component */ function _getNormalizedTargetUnit(ISetToken _setToken, IERC20 _component) internal view returns(uint256) { // (targetUnit * current position multiplier) / position multiplier when rebalance started return executionInfo[_setToken][_component] .targetUnit .mul(_setToken.positionMultiplier().toUint256()) .div(rebalanceInfo[_setToken].positionMultiplier); } /** * Gets unit and notional amount values for current position and target. These are necessary * to calculate the trade size and direction for regular trades and the `sendQuantity` for * remainingWEth trades. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to calculate notional amounts for * @param _totalSupply SetToken total supply * * @return uint256 Current default position real unit of component * @return uint256 Normalized unit of the trade target * @return uint256 Current notional amount: total notional amount of SetToken default position * @return uint256 Target notional amount: Total SetToken supply * targetUnit */ function _getUnitsAndNotionalAmounts(ISetToken _setToken, IERC20 _component, uint256 _totalSupply) internal view returns (uint256, uint256, uint256, uint256) { uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component); uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component); return ( currentUnit, targetUnit, _totalSupply.getDefaultTotalNotional(currentUnit), _totalSupply.preciseMulCeil(targetUnit) ); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /* * Trader must be permissioned for SetToken */ function _validateOnlyAllowedTrader(ISetToken _setToken) internal view { require(_isAllowedTrader(_setToken, msg.sender), "Address not permitted to trade"); } /* * Trade must be an EOA if `anyoneTrade` has been enabled for SetToken on the module. */ function _validateOnlyEOAIfUnrestricted(ISetToken _setToken) internal view { if(permissionInfo[_setToken].anyoneTrade) { require(msg.sender == tx.origin, "Caller must be EOA Address"); } } } // 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 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.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } /* Copyright 2021 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIndexExchangeAdapter { function getSpender() external view returns(address); /** * Returns calldata for executing trade on given adapter's exchange when using the GeneralIndexModule. * * @param _sourceToken Address of source token to be sold * @param _destinationToken Address of destination token to buy * @param _destinationAddress Address that assets should be transferred to * @param _isSendTokenFixed Boolean indicating if the send quantity is fixed, used to determine correct trade interface * @param _sourceQuantity Fixed/Max amount of source token to sell * @param _destinationQuantity Min/Fixed amount of destination tokens to receive * @param _data Arbitrary bytes that can be used to store exchange specific parameters or logic * * @return address Target contract address * @return uint256 Call value * @return bytes Trade calldata */ function getTradeCalldata( address _sourceToken, address _destinationToken, address _destinationAddress, bool _isSendTokenFixed, uint256 _sourceQuantity, uint256 _destinationQuantity, bytes memory _data ) external view returns (address, uint256, bytes memory); } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* 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.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Set Protocol * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw( uint256 wad ) external; } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; import { IController } from "../../interfaces/IController.sol"; import { IModule } from "../../interfaces/IModule.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "./Invoke.sol"; import { Position } from "./Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "./ResourceIdentifier.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title Uint256ArrayUtils * @author Set Protocol * * Utility functions to handle Uint256 Arrays */ library Uint256ArrayUtils { /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUints = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUints[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUints[aLength + j] = B[j]; } return newUints; } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IController } from "../../interfaces/IController.sol"; import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: 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); } 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); } } } } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); }
* Gets unit and notional amount values for current position and target. These are necessary to calculate the trade size and direction for regular trades and the `sendQuantity` for remainingWEth trades. @param _setToken Instance of the SetToken to rebalance @param _component IERC20 component to calculate notional amounts for @param _totalSupply SetToken total supply @return uint256 Current default position real unit of component @return uint256 Normalized unit of the trade target @return uint256 Current notional amount: total notional amount of SetToken default position @return uint256 Target notional amount: Total SetToken supply targetUnit/
function _getUnitsAndNotionalAmounts(ISetToken _setToken, IERC20 _component, uint256 _totalSupply) internal view returns (uint256, uint256, uint256, uint256) { uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component); uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component); return ( currentUnit, targetUnit, _totalSupply.getDefaultTotalNotional(currentUnit), _totalSupply.preciseMulCeil(targetUnit) ); }
6,960,922
[ 1, 3002, 2836, 471, 486, 285, 287, 3844, 924, 364, 783, 1754, 471, 1018, 18, 8646, 854, 4573, 358, 4604, 326, 18542, 963, 471, 4068, 364, 6736, 1284, 5489, 471, 326, 1375, 4661, 12035, 68, 364, 4463, 6950, 451, 1284, 5489, 18, 225, 389, 542, 1345, 1171, 5180, 434, 326, 1000, 1345, 358, 283, 12296, 225, 389, 4652, 7734, 467, 654, 39, 3462, 1794, 358, 4604, 486, 285, 287, 30980, 364, 225, 389, 4963, 3088, 1283, 2868, 1000, 1345, 2078, 14467, 327, 2254, 5034, 2868, 6562, 805, 1754, 2863, 2836, 434, 1794, 327, 2254, 5034, 2868, 8769, 1235, 2836, 434, 326, 18542, 1018, 327, 2254, 5034, 2868, 6562, 486, 285, 287, 3844, 30, 2078, 486, 285, 287, 3844, 434, 1000, 1345, 805, 1754, 327, 2254, 5034, 2868, 5916, 486, 285, 287, 3844, 30, 10710, 1000, 1345, 14467, 225, 1018, 2802, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 7537, 1876, 1248, 285, 287, 6275, 87, 12, 45, 694, 1345, 389, 542, 1345, 16, 467, 654, 39, 3462, 389, 4652, 16, 2254, 5034, 389, 4963, 3088, 1283, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 783, 2802, 273, 389, 588, 1868, 2555, 6955, 2802, 24899, 542, 1345, 16, 389, 4652, 1769, 203, 3639, 2254, 5034, 1018, 2802, 273, 389, 588, 15577, 2326, 2802, 24899, 542, 1345, 16, 389, 4652, 1769, 203, 203, 3639, 327, 261, 203, 5411, 783, 2802, 16, 203, 5411, 1018, 2802, 16, 203, 5411, 389, 4963, 3088, 1283, 18, 588, 1868, 5269, 1248, 285, 287, 12, 2972, 2802, 3631, 203, 5411, 389, 4963, 3088, 1283, 18, 4036, 784, 27860, 39, 73, 330, 12, 3299, 2802, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0x02762ec5CD245d922BE81BcfC6Cc4424eF85166f/sources/project_/contracts/libs/token/BEP20/BEP20Extended.sol
* @dev Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements - `to` cannot be the zero address./
function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); require(totalSupply().add(amount) <= _cap, "BEP20Capped: cap exceeded"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
3,226,410
[ 1, 2729, 1375, 8949, 68, 2430, 471, 22698, 2182, 358, 1375, 4631, 9191, 21006, 326, 2078, 14467, 18, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 2080, 68, 444, 358, 326, 3634, 1758, 18, 29076, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 296, 5948, 52, 3462, 30, 312, 474, 358, 326, 3634, 1758, 8284, 203, 3639, 2583, 12, 4963, 3088, 1283, 7675, 1289, 12, 8949, 13, 1648, 389, 5909, 16, 315, 5948, 52, 3462, 4664, 1845, 30, 3523, 12428, 8863, 203, 203, 3639, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1289, 12, 8949, 1769, 203, 3639, 389, 70, 26488, 63, 4631, 65, 273, 389, 70, 26488, 63, 4631, 8009, 1289, 12, 8949, 1769, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 2236, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GNU General Public License pragma solidity 0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title An implementation of an online marketplace using Ethereum /// @author Rodrigo Ortega /// @notice You can use this contract for actions related to the online marketplace (listing items, buying items, etc.) contract OnlineMarketplace is Ownable { event StoreCreated(string newStoreName, address owner, uint storeID); event StoreUpdated(address indexed seller, uint _storeID, string _name, string _description, string _website, string _email); event ProductCreated(string newProductName, uint price, uint SKU, uint quantity, uint uniqueID, address seller, uint storeID); event ProductUpdated(string newProductName, uint price, uint SKU, uint quantity, uint uniqueID, address seller, uint storeID); event ProductSold(uint orderID, uint indexed productID, address indexed buyer, address indexed seller, uint price, string email); event ProductShipped(uint orderID, uint productID, uint trackingNumber, address indexed seller, address indexed buyer); event UserRegistered(address indexed user, string email); /// @dev incremented by 1 to assign unique IDs to stores and products uint internal ID; /// @dev holds contract balance uint public balance; /// @notice bool for circuit breaker used in function modifier requireIsActive() /// @dev value can be toggled using toggleCircuitBreaker() function by contract owner bool public isActive = true; /// @dev struct for properties of a store object struct Stores { string name; address owner; uint storeID; string description; string website; string email; } /// @dev struct for properties of a product object struct Products { string name; string description; uint price; uint SKU; uint quantity; uint uniqueID; bool shipped; uint trackingNumber; address buyer; address payable seller; uint storeID; uint orderID; } /// @dev array used for listing all stores on front page of user-interface (store directory) Stores[] public storesArray; /// @dev mapping of unique ID to Products mapping (uint => Products) public productsMapping; /// @dev mapping of unique ID to Stores mapping (uint => Stores) public storesMapping; /// @dev mapping of address to array of Stores owned by address mapping (address => Stores[]) public stores; /// @dev mapping of Store ID to array of Products available at that store mapping (uint => Products[]) public products; /// @dev mapping of address to string for contact email mapping (address => string) public emails; /// @dev mapping of order ID to product sold mapping (uint => mapping (uint => Products)) public orders; /// @notice modifier placed in functions for circuit breaker /// @dev isActive default value is true; toggle using toggleCircuitBreaker() modifier requireIsActive() { require(isActive == true); _; } /// @notice function increments ID variable to generate unique IDs /// @dev increments variable uint ID by 1 to generate unique IDs for products and stores function getID() public returns (uint) { return ++ID; } /// @notice getter function for array length of Stores array /// @dev called externally, used for displaying list of all stores in front-end /// @return length of Stores array function getArrayLength() external view returns (uint length) { return storesArray.length; } /// @notice getter function for array length of Stores array in mapping (address key) /// @dev called externally, used for displaying list of stores owned by specific address in front-end /// @return length of Stores array in mapping (address key) function getStoresMALength() external view returns (uint) { return stores[msg.sender].length; } /// @notice getter function for array length of Products array in mapping (store ID key) /// @dev called externally, used for displaying list of products owned by specific store ID in front-end /// @param _storeID The unique store ID generated by getID() called during creation of newStore /// @return length of Products array in mapping (store ID key) function getProductsMALength(uint _storeID) external view returns (uint) { return products[_storeID].length; } /// @notice getter function for Products struct values in mapping (unique ID key) - split into A and B functions /// @dev used in testing for retrieving values of Products struct by product ID /// @param _uniqueID The unique product ID generated by getID() called during creation of newProduct function getProductA (uint _uniqueID) external view returns (string memory name, string memory description, uint price, uint SKU, uint quantity, uint uniqueID) { return (productsMapping[_uniqueID].name, productsMapping[_uniqueID].description, productsMapping[_uniqueID].price, productsMapping[_uniqueID].SKU, productsMapping[_uniqueID].quantity, productsMapping[_uniqueID].uniqueID); } /// @notice getter function for Products struct values in mapping (unique ID key)- split into A and B functions /// @dev used in testing for retrieving values of Products struct by product ID /// @param _uniqueID The unique product ID generated by getID() called during creation of newProduct function getProductB (uint _uniqueID) external view returns (bool shipped, uint trackingNumber, address buyer, address seller, uint storeID, uint orderID) { return (productsMapping[_uniqueID].shipped, productsMapping[_uniqueID].trackingNumber, productsMapping[_uniqueID].buyer, productsMapping[_uniqueID].seller, productsMapping[_uniqueID].storeID, productsMapping[_uniqueID].orderID); } /// @notice getter function for mapping of array of Product structs (store ID key) /// @dev called externally, used for retrieving products by store ID in front-end /// @param _storeID The unique store ID /// @param _index The index value for the location of the Product struct in the array /// @return name of the product function getProductsMA(uint _storeID, uint _index) external view returns (string memory) { return products[_storeID][_index].name; } /// @notice getter function for Stores struct in mapping (store ID key) /// @dev returns Stores struct values from mapping (store ID key) in front-end /// @param _storeID The unique store ID /// @return name of the store function getStore(uint _storeID) external view returns (string memory) { return storesMapping[_storeID].name; } /// @notice getter function for mapping of email addresses (address key) /// @dev called externally, used for retrieving a person's email address using thee associated Ethereum public address in front-end /// @param _address The person's Ethereum public address /// @return email address function getEmail(address _address) external view returns (string memory email, address buyer) { return (emails[_address], _address); } /// @notice getter function for contract's current balance /// @dev called externally, used for retrieving contract's current balance in front-end /// @return current balance of this contract function getContractBalance() external view returns (uint) { return address(this).balance; } /// @notice function for creating a new store /// @dev built in circuit-breaker; called externally, used for creating a new Store object /// @param _name The store's name /// @param _description The store's description /// @param _website The store's website /// @param _email The store's contact email address function newStore(string calldata _name, string calldata _description, string calldata _website, string calldata _email) external payable requireIsActive { require (msg.value == .005 ether); balance += msg.value; Stores memory a; a.name = _name; a.owner = msg.sender; a.storeID = getID(); a.description = _description; a.website = _website; a.email = _email; insertStore(a, a.storeID); emit StoreCreated(_name, msg.sender, a.storeID); } /// @dev private function, called during previous function to add new Store object to storage variables function insertStore(Stores memory a, uint _storeID) private { stores[msg.sender].push(a); storesMapping[_storeID] = a; storesArray.push(a); } /// @notice function for creating a new product /// @dev built-in circuit breaker; called externally, used for creating a new Product object /// @param _name The product's name /// @param _description The product's description /// @param _price The product's price /// @param _SKU The product's SKU /// @param _quantity The product's quantity /// @param _storeID The unique ID of the product's associated store function newProduct(string calldata _name, string calldata _description, uint _price, uint _SKU, uint _quantity, uint _storeID) external payable requireIsActive { require (msg.value == .001 ether); balance += msg.value; Products memory c; c.name = _name; c.description = _description; c.price = _price; c.SKU = _SKU; c.quantity = _quantity; uint abc = getID(); c.uniqueID = abc; c.seller = msg.sender; c.storeID = _storeID; insertProduct(c, _storeID, abc); emit ProductCreated(_name, _price, _SKU, _quantity, abc, msg.sender, c.storeID); } /// @dev private function, called during previous function to add new Product object to storage variables function insertProduct(Products memory c, uint storeID, uint _uniqueID) private { products[storeID].push(c); productsMapping[_uniqueID] = c; } /// @notice function for editing an existing product /// @dev built-in circuit breaker; called externally, used for editing an existing, listed Product /// @param _index The product's index # in the products array /// @param _name The product's name /// @param _description The product's description /// @param _price The product's price /// @param _SKU The product's SKU /// @param _quantity The product's quantity /// @param _storeID The unique ID of the product's associated store /// @param _uniqueID The product's unique ID function editProduct(uint _index, string calldata _name, string calldata _description, uint _price, uint _SKU, uint _quantity, uint _storeID, uint _uniqueID) external requireIsActive { products[_storeID][_index].name = _name; products[_storeID][_index].description = _description; products[_storeID][_index].price = _price; products[_storeID][_index].SKU = _SKU; products[_storeID][_index].quantity = _quantity; productsMapping[_uniqueID].name = _name; productsMapping[_uniqueID].description = _description; productsMapping[_uniqueID].price = _price; productsMapping[_uniqueID].SKU = _SKU; productsMapping[_uniqueID].quantity = _quantity; emit ProductUpdated(_name, _price, _SKU, _quantity, _uniqueID, msg.sender, _storeID); } /// @notice function for editing an existing store /// @dev built-in circuit breaker; called externally, used for editing an existing, listed store /// @param _index The store's index # in the stores array /// @param _storeID The unique ID of the store /// @param _name The store's name /// @param _description The store's description /// @param _website The store's website /// @param _email The store's email function editStore(uint _index, uint _storeID, string calldata _name, string calldata _description, string calldata _website, string calldata _email) external requireIsActive { require(storesMapping[_storeID].owner == msg.sender); stores[msg.sender][_index].name = _name; stores[msg.sender][_index].description = _description; stores[msg.sender][_index].website = _website; stores[msg.sender][_index].email = _email; storesMapping[_storeID].name = _name; storesMapping[_storeID].description = _description; storesMapping[_storeID].website = _website; storesMapping[_storeID].email = _email; emit StoreUpdated(msg.sender, _storeID, _name, _description, _website, _email); } /// @notice function executed when purchasing a product /// @dev called externally, checks for the product price to be equal to tx value sent and that product is in stock, then sets "sold" property to true and sends value to seller /// @param _productID The product's unique ID function buyItem(uint _productID) external payable requireIsActive { require (msg.value == productsMapping[_productID].price); require (productsMapping[_productID].quantity > 0); require (bytes(emails[msg.sender]).length > 0, "You need to register an email address before purchasing an item."); productsMapping[_productID].seller.transfer(msg.value); productsMapping[_productID].quantity -= 1; uint orderID = getID(); orders[orderID][_productID] = productsMapping[_productID]; orders[orderID][_productID].buyer = msg.sender; orders[orderID][_productID].orderID = orderID; emit ProductSold(orderID,_productID, msg.sender, productsMapping[_productID].seller, productsMapping[_productID].price, emails[msg.sender]); } /// @notice setter function for updating trackingNumber once product is shipped /// @dev called externally by seller, used for updating trackingNumber and shipped values in mapping of Products (_uniqueID key) /// @param _orderID The order ID associated with the product being shipped /// @param _productID The product's unique ID /// @param _trackingNumber The product's tracking number when shipped function itemShipped(uint _orderID, uint _productID, uint _trackingNumber) external { require(orders[_orderID][_productID].seller == msg.sender); orders[_orderID][_productID].trackingNumber = _trackingNumber; orders[_orderID][_productID].shipped = true; emit ProductShipped(_orderID, _productID, _trackingNumber, productsMapping[_productID].seller, orders[_orderID][_productID].buyer); } /// @notice function to register an email address /// @dev updates mapping of email addresses using msg.sender as key (address key) /// @param _email email address of the person calling the function function register(string calldata _email) external requireIsActive { emails[msg.sender] = _email; emit UserRegistered(msg.sender, _email); } /// @notice getter function for retrieving the contract's current balance /// @dev called externally, used for updating the contract's current balance in the front-end /// @return balance, The contract's current balance function getBalance() external view returns (uint) { return address(this).balance; } /// @notice function to withdraw all funds from the contract /// @dev built-in circuit breaker; called externally by contract owner, used for withdrawing all available funds in the contract function withdrawAll() external onlyOwner requireIsActive { uint toTransfer = balance; balance = 0; msg.sender.transfer(toTransfer); } /// @notice function to initiate the contract's circuit breaker (freeze certain contract functions) /// @dev called externally by contract's owner, toggles isActive bool variable to enable or disable circuit breaker function toggleCircuitBreaker() external onlyOwner { isActive = !isActive; } }
@dev mapping of order ID to product sold
mapping (uint => mapping (uint => Products)) public orders;
15,821,288
[ 1, 6770, 434, 1353, 1599, 358, 3017, 272, 1673, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 11890, 516, 2874, 261, 11890, 516, 8094, 87, 3719, 1071, 11077, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IHologramAccumulator.sol"; /// @title HologramAccumulator - counts the behavior. /// @author Shumpei Koike - <[email protected]> contract TestHologramAccumulator is IHologramAccumulator { using Address for address; uint256 public constant DENOMINATOR = 1000; mapping(address => uint256) private _weighted; mapping(address => uint256) private _accumulate; /// Events event Accumulate(address caller, address account, uint256 weight); event AccumulateBatch(address caller, address[2] accounts, uint256 weight); event AccumulateBatch(address caller, address[3] accounts, uint256 weight); event Undermine(address caller, address account, uint256 weight); event UndermineBatch(address caller, address[2] accounts, uint256 weight); event UndermineBatch(address caller, address[3] accounts, uint256 weight); event ChangeCoefficient(address accessor, uint256 coefficient); event Accept(address accessor); /// @dev Counts a positive behavior. /// @param account address who behaves positively function accumulateSmall(address account) public override { _accumulate[account]++; emit Accumulate(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param account address who behaves positively function accumulateMedium(address account) public override { _accumulate[account] += 2; emit Accumulate(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param account address who behaves positively function accumulateLarge(address account) public override { _accumulate[account] += 3; emit Accumulate(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch2Small(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]]++; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch2Medium(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 2; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch2Large(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 3; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch3Small(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]]++; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch3Medium(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 2; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch3Large(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 3; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param account address who behaves negatively function undermineSmall(address account) public override { _accumulate[account] > 0 ? _accumulate[account]-- : _accumulate[account] = 0; emit Undermine(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param account address who behaves negatively function undermineMedium(address account) public override { _accumulate[account] > 1 ? _accumulate[account] -= 2 : _accumulate[account] = 0; emit Undermine(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param account address who behaves negatively function undermineLarge(address account) public override { _accumulate[account] > 2 ? _accumulate[account] -= 3 : _accumulate[account] = 0; emit Undermine(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch2Small(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 0 ? _accumulate[accounts[i]]-- : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch2Medium(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 1 ? _accumulate[accounts[i]] -= 2 : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch2Large(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 2 ? _accumulate[accounts[i]] -= 3 : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch3Small(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 0 ? _accumulate[accounts[i]]-- : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch3Medium(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 1 ? _accumulate[accounts[i]] -= 2 : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch3Large(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 2 ? _accumulate[accounts[i]] -= 3 : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } }
Events @dev Counts a positive behavior. @param account address who behaves positively
function accumulateSmall(address account) public override { _accumulate[account]++; emit Accumulate(msg.sender, account, _weighted[msg.sender]); }
12,551,663
[ 1, 3783, 225, 6974, 87, 279, 6895, 6885, 18, 225, 2236, 1758, 10354, 12433, 6606, 949, 305, 4492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 21757, 19187, 12, 2867, 2236, 13, 1071, 3849, 288, 203, 202, 202, 67, 8981, 31284, 63, 4631, 3737, 15, 31, 203, 202, 202, 18356, 15980, 31284, 12, 3576, 18, 15330, 16, 2236, 16, 389, 30890, 63, 3576, 18, 15330, 19226, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.7; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; // @title Airdrop proxy contract for BLT // @author Dustin van Schouwen // @notice Handles simple airdrops for BLT contract AirdropProxy is Ownable, Pausable { using SafeERC20 for ERC20; ERC20 public token; // @notice Mapping to describe which addresses are managers mapping(address => bool) managers_map; event AddManager(address _address); event RemoveManager(address _address); // @notice Initializes contract constructor(ERC20 _token) public { token = _token; managers_map[msg.sender] = true; } // @notice Prevents non-managers from running some functions modifier onlyManager { require(managers_map[msg.sender], "Must be a manager"); _; } // @notice Function for owner of contract to add new manager function addManager(address _manager) public onlyOwner { managers_map[_manager] = true; emit AddManager(_manager); } // @notice Function for owner of contract to remove manager function removeManager(address _oldManager) public onlyOwner { require(isManager(_oldManager), "Address is not currently a manager"); managers_map[_oldManager] = false; emit RemoveManager(_oldManager); } // @notice Function for a contract manager to airdrop BLT to an address function airdrop(address _to, uint256 _amount) public onlyManager whenNotPaused { require(token.balanceOf(address(this)) > _amount, "Not enough tokens to fulfill"); require(_amount < 10 ether, "Amount exceeds max allowed amount"); token.transfer(_to, _amount); } // @notice Function to return true/false re: an address being a manager function isManager(address _address) public view returns (bool) { return managers_map[_address] == true; } // @notice Function to withdraw all tokens from contract function withdrawAllTokens(address _to) public onlyOwner { token.transfer(_to, token.balanceOf(address(this))); } }
@notice Function to return true/false re: an address being a manager
function isManager(address _address) public view returns (bool) { return managers_map[_address] == true; }
5,404,534
[ 1, 2083, 358, 327, 638, 19, 5743, 283, 30, 392, 1758, 3832, 279, 3301, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 353, 1318, 12, 2867, 389, 2867, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 21103, 67, 1458, 63, 67, 2867, 65, 422, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity 0.7.5; pragma abicoder v2; import "./StakingLockable.sol"; /// @author umb.network /// @notice Math is based on synthetix staking contract /// Contract allows to stake and lock tokens. For rUMB tokens only locking option is available. /// When locking user choose period and based on period multiplier is apply to the amount (boost). /// If pool is set for rUMB1->rUMB2, (rUmbPool) then rUMB2 can be locked as well contract StakingLens { struct LockData { uint256 period; uint256 multiplier; } /// @dev returns amount of all staked and locked tokens including bonuses function balanceOf(StakingLockable _pool, address _account) external view returns (uint256) { (uint96 umbBalance, uint96 lockedWithBonus,,,) = _pool.balances(_account); return umbBalance + lockedWithBonus; } function getRewardForDuration(StakingLockable _pool) external view returns (uint256) { (, uint32 rewardsDuration,,) = _pool.timeData(); return _pool.rewardRate() * rewardsDuration; } function rewards(StakingLockable _pool, address _user) external view returns (uint256) { (,,,,uint96 userRewards) = _pool.balances(_user); return userRewards; } /// @notice returns array of max 100 booleans, where index corresponds to lock id. `true` means lock can be withdraw function getVestedLockIds(StakingLockable _pool, address _account, uint256 _offset) external view returns (bool[] memory results) { (,,uint256 nextLockIndex,,) = _pool.balances(_account); uint256 batch = 100; if (nextLockIndex == 0) return results; if (nextLockIndex <= _offset) return results; uint256 end = _offset + batch > nextLockIndex ? nextLockIndex : _offset + batch; results = new bool[](end); for (uint256 i = _offset; i < end; i++) { (,,, uint32 unlockDate,, uint32 withdrawnAt) = _pool.locks(_account, i); results[i] = withdrawnAt == 0 && unlockDate <= block.timestamp; } } /// @notice returns array of max 100 booleans, where index corresponds to lock id. /// `true` means lock was not withdrawn yet function getActiveLockIds(StakingLockable _pool, address _account, uint256 _offset) external view returns (bool[] memory results) { (,,uint256 nextLockIndex,,) = _pool.balances(_account); uint256 batch = 100; if (nextLockIndex == 0) return results; if (nextLockIndex <= _offset) return results; uint256 end = _offset + batch > nextLockIndex ? nextLockIndex : _offset + batch; results = new bool[](end); for (uint256 i = _offset; i < end; i++) { (,,,,, uint32 withdrawnAt) = _pool.locks(_account, i); results[i] = withdrawnAt == 0; } } function getPeriods(StakingLockable _pool, address _token) external view returns (uint256[] memory periods) { return _pool.getPeriods(_token); } function getPeriodsAndMultipliers(StakingLockable _pool, address _token) external view returns (LockData[] memory lockData) { uint256[] memory periods = _pool.getPeriods(_token); uint256 n = periods.length; lockData = new LockData[](n); for (uint256 i; i < n; i++) { lockData[i] = LockData(periods[i], _pool.multipliers(_token, periods[i])); } } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // Inheritance import "../interfaces/IStakingRewards.sol"; import "../interfaces/Pausable.sol"; import "../interfaces/IBurnableToken.sol"; import "../interfaces/RewardsDistributionRecipient.sol"; import "../interfaces/OnDemandToken.sol"; import "../interfaces/LockSettings.sol"; import "../interfaces/SwappableTokenV2.sol"; /// @author umb.network /// @notice Math is based on synthetix staking contract /// Contract allows to stake and lock tokens. For rUMB tokens only locking option is available. /// When locking user choose period and based on period multiplier is apply to the amount (boost). /// If pool is set for rUMB1->rUMB2, (rUmbPool) then rUMB2 can be locked as well contract StakingLockable is LockSettings, RewardsDistributionRecipient, ReentrancyGuard, Pausable { struct Times { uint32 periodFinish; uint32 rewardsDuration; uint32 lastUpdateTime; uint96 totalRewardsSupply; } struct Balance { // total supply of UMB = 500_000_000e18, it can be saved using 89bits, so we good with 96 and above // user UMB balance uint96 umbBalance; // amount locked + virtual balance generated using multiplier when locking uint96 lockedWithBonus; uint32 nextLockIndex; uint160 userRewardPerTokenPaid; uint96 rewards; } struct Supply { // staked + raw locked uint128 totalBalance; // virtual balance uint128 totalBonus; } struct Lock { uint8 tokenId; // total supply of UMB can be saved using 89bits, so we good with 96 and above uint120 amount; uint32 lockDate; uint32 unlockDate; uint32 multiplier; uint32 withdrawnAt; } uint8 public constant UMB_ID = 2 ** 0; uint8 public constant RUMB1_ID = 2 ** 1; uint8 public constant RUMB2_ID = 2 ** 2; uint256 public immutable maxEverTotalRewards; address public immutable umb; address public immutable rUmb1; /// @dev this is reward token but we also allow to lock it address public immutable rUmb2; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored; Supply public totalSupply; Times public timeData; /// @dev user => Balance mapping(address => Balance) public balances; /// @dev user => lock ID => Lock mapping(address => mapping(uint256 => Lock)) public locks; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount, uint256 bonus); event LockedTokens( address indexed user, address indexed token, uint256 lockId, uint256 amount, uint256 period, uint256 multiplier ); event UnlockedTokens(address indexed user, address indexed token, uint256 lockId, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event FarmingFinished(); event Swap1to2(uint256 swapped); modifier updateReward(address _account) virtual { uint256 newRewardPerTokenStored = rewardPerToken(); rewardPerTokenStored = newRewardPerTokenStored; timeData.lastUpdateTime = uint32(lastTimeRewardApplicable()); if (_account != address(0)) { balances[_account].rewards = uint96(earned(_account)); balances[_account].userRewardPerTokenPaid = uint160(newRewardPerTokenStored); } _; } constructor( address _owner, address _rewardsDistribution, address _umb, address _rUmb1, address _rUmb2 ) Owned(_owner) { require( ( MintableToken(_umb).maxAllowedTotalSupply() + MintableToken(_rUmb1).maxAllowedTotalSupply() + MintableToken(_rUmb2).maxAllowedTotalSupply() ) * MAX_MULTIPLIER / RATE_DECIMALS <= type(uint96).max, "staking overflow" ); require( MintableToken(_rUmb2).maxAllowedTotalSupply() * MAX_MULTIPLIER / RATE_DECIMALS <= type(uint96).max, "rewards overflow" ); require(OnDemandToken(_rUmb2).ON_DEMAND_TOKEN(), "rewardsToken must be OnDemandToken"); umb = _umb; rUmb1 = _rUmb1; rUmb2 = _rUmb2; rewardsDistribution = _rewardsDistribution; timeData.rewardsDuration = 2592000; // 30 days maxEverTotalRewards = MintableToken(_rUmb2).maxAllowedTotalSupply(); } function lockTokens(address _token, uint256 _amount, uint256 _period) external { if (_token == rUmb2 && !SwappableTokenV2(rUmb2).isSwapStarted()) { revert("locking rUMB2 not available yet"); } _lockTokens(msg.sender, _token, _amount, _period); } function unlockTokens(uint256[] calldata _ids) external { _unlockTokensFor(msg.sender, _ids, msg.sender); } function restart(uint256 _rewardsDuration, uint256 _reward) external { setRewardsDuration(_rewardsDuration); notifyRewardAmount(_reward); } // when farming was started with 1y and 12tokens // and we want to finish after 4 months, we need to end up with situation // like we were starting with 4mo and 4 tokens. function finishFarming() external onlyOwner { Times memory t = timeData; require(block.timestamp < t.periodFinish, "can't stop if not started or already finished"); if (totalSupply.totalBalance != 0) { uint32 remaining = uint32(t.periodFinish - block.timestamp); timeData.rewardsDuration = t.rewardsDuration - remaining; } timeData.periodFinish = uint32(block.timestamp); emit FarmingFinished(); } /// @notice one of the reasons this method can throw is, when we swap for UMB and somebody stake rUMB1 after that. /// In that case execution of `swapForUMB()` is required (anyone can execute this method) before proceeding. function exit() external { _withdraw(type(uint256).max, msg.sender, msg.sender); _getReward(msg.sender, msg.sender); } /// @notice one of the reasons this method can throw is, when we swap for UMB and somebody stake rUMB1 after that. /// In that case execution of `swapForUMB()` is required (anyone can execute this method) before proceeding. function exitAndUnlock(uint256[] calldata _lockIds) external { _withdraw(type(uint256).max, msg.sender, msg.sender); _unlockTokensFor(msg.sender, _lockIds, msg.sender); _getReward(msg.sender, msg.sender); } function stake(uint256 _amount) external { _stake(umb, msg.sender, _amount, 0); } function getReward() external { _getReward(msg.sender, msg.sender); } function swap1to2() public { if (!SwappableTokenV2(rUmb2).isSwapStarted()) return; uint256 myBalance = IERC20(rUmb1).balanceOf(address(this)); if (myBalance == 0) return; IBurnableToken(rUmb1).burn(myBalance); OnDemandToken(rUmb2).mint(address(this), myBalance); emit Swap1to2(myBalance); } /// @dev when notifying about amount, we don't have to mint or send any tokens, reward tokens will be mint on demand /// this method is used to restart staking function notifyRewardAmount( uint256 _reward ) override public onlyRewardsDistribution updateReward(address(0)) { // this method can be executed on its own as well, I'm including here to not need to remember about it swap1to2(); Times memory t = timeData; uint256 newRewardRate; if (block.timestamp >= t.periodFinish) { newRewardRate = _reward / t.rewardsDuration; } else { uint256 remaining = t.periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; newRewardRate = (_reward + leftover) / t.rewardsDuration; } require(newRewardRate != 0, "invalid rewardRate"); rewardRate = newRewardRate; // always increasing by _reward even if notification is in a middle of period // because leftover is included uint256 totalRewardsSupply = timeData.totalRewardsSupply + _reward; require(totalRewardsSupply <= maxEverTotalRewards, "rewards overflow"); timeData.totalRewardsSupply = uint96(totalRewardsSupply); timeData.lastUpdateTime = uint32(block.timestamp); timeData.periodFinish = uint32(block.timestamp + t.rewardsDuration); emit RewardAdded(_reward); } function setRewardsDuration(uint256 _rewardsDuration) public onlyRewardsDistribution { require(_rewardsDuration != 0, "empty _rewardsDuration"); require( block.timestamp > timeData.periodFinish, "Previous period must be complete before changing the duration" ); timeData.rewardsDuration = uint32(_rewardsDuration); emit RewardsDurationUpdated(_rewardsDuration); } /// @notice one of the reasons this method can throw is, when we swap for UMB and somebody stake rUMB1 after that. /// In that case execution of `swapForUMB()` is required (anyone can execute this method) before proceeding. function withdraw(uint256 _amount) public { _withdraw(_amount, msg.sender, msg.sender); } function lastTimeRewardApplicable() public view returns (uint256) { uint256 periodFinish = timeData.periodFinish; return block.timestamp < periodFinish ? block.timestamp : periodFinish; } function rewardPerToken() public view returns (uint256 perToken) { Supply memory s = totalSupply; if (s.totalBalance == 0) { return rewardPerTokenStored; } perToken = rewardPerTokenStored + ( (lastTimeRewardApplicable() - timeData.lastUpdateTime) * rewardRate * 1e18 / (s.totalBalance + s.totalBonus) ); } function earned(address _account) virtual public view returns (uint256) { Balance memory b = balances[_account]; uint256 totalBalance = b.umbBalance + b.lockedWithBonus; return (totalBalance * (rewardPerToken() - b.userRewardPerTokenPaid) / 1e18) + b.rewards; } function calculateBonus(uint256 _amount, uint256 _multiplier) public pure returns (uint256 bonus) { if (_multiplier <= RATE_DECIMALS) return 0; bonus = _amount * _multiplier / RATE_DECIMALS - _amount; } /// @param _token token that we allow to stake, validator check should be do outside /// @param _user token owner /// @param _amount amount /// @param _bonus if bonus is 0, means we are staking, bonus > 0 means this is locking function _stake(address _token, address _user, uint256 _amount, uint256 _bonus) internal nonReentrant notPaused updateReward(_user) { uint256 amountWithBonus = _amount + _bonus; require(timeData.periodFinish > block.timestamp, "Stake period not started yet"); require(amountWithBonus != 0, "Cannot stake 0"); // TODO check if we ever need to separate balance and bonuses totalSupply.totalBalance += uint96(_amount); totalSupply.totalBonus += uint128(_bonus); if (_bonus == 0) { balances[_user].umbBalance += uint96(_amount); } else { balances[_user].lockedWithBonus += uint96(amountWithBonus); } // not using safe transfer, because we working with trusted tokens require(IERC20(_token).transferFrom(_user, address(this), _amount), "token transfer failed"); emit Staked(_user, _amount, _bonus); } function _lockTokens(address _user, address _token, uint256 _amount, uint256 _period) internal notPaused { uint256 multiplier = multipliers[_token][_period]; require(multiplier != 0, "invalid period or not supported token"); uint256 stakeBonus = calculateBonus(_amount, multiplier); _stake(_token, _user, _amount, stakeBonus); _addLock(_user, _token, _amount, _period, multiplier); } function _addLock(address _user, address _token, uint256 _amount, uint256 _period, uint256 _multiplier) internal { uint256 newIndex = balances[_user].nextLockIndex; if (newIndex == type(uint32).max) revert("nextLockIndex overflow"); balances[_user].nextLockIndex = uint32(newIndex + 1); Lock storage lock = locks[_user][newIndex]; lock.amount = uint120(_amount); lock.multiplier = uint32(_multiplier); lock.lockDate = uint32(block.timestamp); lock.unlockDate = uint32(block.timestamp + _period); if (_token == rUmb2) lock.tokenId = RUMB2_ID; else if (_token == rUmb1) lock.tokenId = RUMB1_ID; else lock.tokenId = UMB_ID; emit LockedTokens(_user, _token, newIndex, _amount, _period, _multiplier); } // solhint-disable-next-line code-complexity function _unlockTokensFor(address _user, uint256[] calldata _indexes, address _recipient) internal returns (address token, uint256 totalRawAmount) { uint256 totalBonus; uint256 acceptedTokenId; bool isSwapStarted = SwappableTokenV2(rUmb2).isSwapStarted(); for (uint256 i; i < _indexes.length; i++) { (uint256 amount, uint256 bonus, uint256 tokenId) = _markAsUnlocked(_user, _indexes[i]); if (amount == 0) continue; if (acceptedTokenId == 0) { acceptedTokenId = tokenId; token = _idToToken(tokenId); // if token is already rUmb2 means swap started already if (token == rUmb1 && isSwapStarted) { token = rUmb2; acceptedTokenId = RUMB2_ID; } } else if (acceptedTokenId != tokenId) { if (acceptedTokenId == RUMB2_ID && tokenId == RUMB1_ID) { // this lock is for rUMB1 but swap 1->2 is started so we unlock as rUMB2 } else revert("batch unlock possible only for the same tokens"); } emit UnlockedTokens(_user, token, _indexes[i], amount); totalRawAmount += amount; totalBonus += bonus; } if (totalRawAmount == 0) revert("nothing to unlock"); _withdrawUnlockedTokens(_user, token, _recipient, totalRawAmount, totalBonus); } function _withdrawUnlockedTokens( address _user, address _token, address _recipient, uint256 _totalRawAmount, uint256 _totalBonus ) internal { uint256 amountWithBonus = _totalRawAmount + _totalBonus; balances[_user].lockedWithBonus -= uint96(amountWithBonus); totalSupply.totalBalance -= uint96(_totalRawAmount); totalSupply.totalBonus -= uint128(_totalBonus); // note: there is one case when this transfer can fail: // when swap is started by we did not swap rUmb1 -> rUmb2, // in that case we have to execute `swap1to2` // to save gas I'm not including it here, because it is unlikely case require(IERC20(_token).transfer(_recipient, _totalRawAmount), "withdraw unlocking failed"); } function _markAsUnlocked(address _user, uint256 _index) internal returns (uint256 amount, uint256 bonus, uint256 tokenId) { // TODO will storage save gas? Lock memory lock = locks[_user][_index]; if (lock.withdrawnAt != 0) revert("DepositAlreadyWithdrawn"); if (block.timestamp < lock.unlockDate) revert("DepositLocked"); if (lock.amount == 0) return (0, 0, 0); locks[_user][_index].withdrawnAt = uint32(block.timestamp); return (lock.amount, calculateBonus(lock.amount, lock.multiplier), lock.tokenId); } /// @param _amount tokens to withdraw /// @param _user address /// @param _recipient address, where to send tokens, if we migrating token address can be zero function _withdraw(uint256 _amount, address _user, address _recipient) internal nonReentrant updateReward(_user) { Balance memory balance = balances[_user]; if (_amount == type(uint256).max) _amount = balance.umbBalance; else require(balance.umbBalance >= _amount, "withdraw amount to high"); if (_amount == 0) return; // not using safe math, because there is no way to overflow because of above check totalSupply.totalBalance -= uint120(_amount); balances[_user].umbBalance = uint96(balance.umbBalance - _amount); // not using safe transfer, because we working with trusted tokens require(IERC20(umb).transfer(_recipient, _amount), "token transfer failed"); emit Withdrawn(_user, _amount); } /// @param _user address /// @param _recipient address, where to send reward function _getReward(address _user, address _recipient) internal nonReentrant updateReward(_user) returns (uint256 reward) { reward = balances[_user].rewards; if (reward != 0) { balances[_user].rewards = 0; OnDemandToken(address(rUmb2)).mint(_recipient, reward); emit RewardPaid(_user, reward); } } function _idToToken(uint256 _tokenId) internal view returns (address token) { if (_tokenId == RUMB2_ID) token = rUmb2; else if (_tokenId == RUMB1_ID) token = rUmb1; else if (_tokenId == UMB_ID) token = umb; else return address(0); } } // 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 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.7.5; interface IStakingRewards { // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "./Owned.sol"; abstract contract Pausable is Owned { bool public paused; event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } constructor() { // This contract is abstract, and thus cannot be instantiated directly require(owner() != address(0), "Owner must be set"); // Paused will be false } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // Let everyone know that our pause state has changed. emit PauseChanged(paused); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface IBurnableToken { function burn(uint256 _amount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "./Owned.sol"; // https://docs.synthetix.io/contracts/RewardsDistributionRecipient abstract contract RewardsDistributionRecipient is Owned { address public rewardsDistribution; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistributor"); _; } function notifyRewardAmount(uint256 reward) virtual external; function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./MintableToken.sol"; abstract contract OnDemandToken is MintableToken { bool constant public ON_DEMAND_TOKEN = true; mapping (address => bool) public minters; event SetupMinter(address minter, bool active); modifier onlyOwnerOrMinter() { address msgSender = _msgSender(); require(owner() == msgSender || minters[msgSender], "access denied"); _; } function setupMinter(address _minter, bool _active) external onlyOwner() { minters[_minter] = _active; emit SetupMinter(_minter, _active); } function setupMinters(address[] calldata _minters, bool[] calldata _actives) external onlyOwner() { for (uint256 i; i < _minters.length; i++) { minters[_minters[i]] = _actives[i]; emit SetupMinter(_minters[i], _actives[i]); } } function mint(address _holder, uint256 _amount) external virtual override onlyOwnerOrMinter() assertMaxSupply(_amount) { require(_amount != 0, "zero amount"); _mint(_holder, _amount); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract LockSettings is Ownable { /// @dev decimals for: baseRate, APY, multipliers /// eg for baseRate: 1e6 is 1%, 50e6 is 50% /// eg for multipliers: 1e6 is 1.0x, 3210000 is 3.21x uint256 public constant RATE_DECIMALS = 10 ** 6; uint256 public constant MAX_MULTIPLIER = 5 * RATE_DECIMALS; /// @notice token => period => multiplier mapping(address => mapping(uint256 => uint256)) public multipliers; /// @notice token => period => index in periods array mapping(address => mapping(uint256 => uint256)) public periodIndexes; /// @notice token => periods mapping(address => uint256[]) public periods; event TokenSettings(address indexed token, uint256 period, uint256 multiplier); function removePeriods(address _token, uint256[] calldata _periods) external onlyOwner { for (uint256 i; i < _periods.length; i++) { if (_periods[i] == 0) revert("InvalidSettings"); multipliers[_token][_periods[i]] = 0; _removePeriod(_token, _periods[i]); emit TokenSettings(_token, _periods[i], 0); } } // solhint-disable-next-line code-complexity function setLockingTokenSettings(address _token, uint256[] calldata _periods, uint256[] calldata _multipliers) external onlyOwner { if (_periods.length == 0) revert("EmptyPeriods"); if (_periods.length != _multipliers.length) revert("ArraysNotMatch"); for (uint256 i; i < _periods.length; i++) { if (_periods[i] == 0) revert("InvalidSettings"); if (_multipliers[i] < RATE_DECIMALS) revert("multiplier must be >= 1e6"); if (_multipliers[i] > MAX_MULTIPLIER) revert("multiplier overflow"); multipliers[_token][_periods[i]] = _multipliers[i]; emit TokenSettings(_token, _periods[i], _multipliers[i]); if (_multipliers[i] == 0) _removePeriod(_token, _periods[i]); else _addPeriod(_token, _periods[i]); } } function periodsCount(address _token) external view returns (uint256) { return periods[_token].length; } function getPeriods(address _token) external view returns (uint256[] memory) { return periods[_token]; } function _addPeriod(address _token, uint256 _period) internal { uint256 key = periodIndexes[_token][_period]; if (key != 0) return; periods[_token].push(_period); // periodIndexes are starting from 1, not from 0 periodIndexes[_token][_period] = periods[_token].length; } function _removePeriod(address _token, uint256 _period) internal { uint256 key = periodIndexes[_token][_period]; if (key == 0) return; periods[_token][key - 1] = periods[_token][periods[_token].length - 1]; periodIndexes[_token][_period] = 0; periods[_token].pop(); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/Owned.sol"; import "../interfaces/ISwapReceiver.sol"; /// @title Umbrella Rewards contract V2 /// @author umb.network /// @notice This contract serves Swap functionality for rewards tokens /// @dev It allows to swap itself for other token (main UMB token). abstract contract SwappableTokenV2 is Owned, ERC20 { struct SwapData { // number of tokens swapped so far (no decimals) uint32 swappedSoFar; // used limit since last swap (no decimals) uint32 usedLimit; // daily cup (no decimals) uint32 dailyCup; uint32 dailyCupTimestamp; uint32 swapEnabledAt; } uint256 public constant ONE = 1e18; uint256 public immutable swapStartsOn; ISwapReceiver public immutable umb; SwapData public swapData; event LogStartEarlySwapNow(uint time); event LogSwap(address indexed swappedTo, uint amount); event LogDailyCup(uint newCup); constructor(address _umb, uint32 _swapStartsOn, uint32 _dailyCup) { require(_dailyCup != 0, "invalid dailyCup"); require(_swapStartsOn > block.timestamp, "invalid swapStartsOn"); require(ERC20(_umb).decimals() == 18, "invalid UMB token"); swapStartsOn = _swapStartsOn; umb = ISwapReceiver(_umb); swapData.dailyCup = _dailyCup; } function swapForUMB() external { SwapData memory data = swapData; (uint256 limit, bool fullLimit) = _currentLimit(data); require(limit != 0, "swapping period not started OR limit"); uint256 amountToSwap = balanceOf(msg.sender); require(amountToSwap != 0, "you dont have tokens to swap"); uint32 amountWoDecimals = uint32(amountToSwap / ONE); require(amountWoDecimals <= limit, "daily CUP limit"); swapData.usedLimit = uint32(fullLimit ? amountWoDecimals : data.usedLimit + amountWoDecimals); swapData.swappedSoFar += amountWoDecimals; if (fullLimit) swapData.dailyCupTimestamp = uint32(block.timestamp); _burn(msg.sender, amountToSwap); umb.swapMint(msg.sender, amountToSwap); emit LogSwap(msg.sender, amountToSwap); } function startEarlySwap() external onlyOwner { require(block.timestamp < swapStartsOn, "swap is already allowed"); require(swapData.swapEnabledAt == 0, "swap was already enabled"); swapData.swapEnabledAt = uint32(block.timestamp); emit LogStartEarlySwapNow(block.timestamp); } /// @param _cup daily cup limit (no decimals), eg. if cup=5 means it is 5 * 10^18 tokens function setDailyCup(uint32 _cup) external onlyOwner { swapData.dailyCup = _cup; emit LogDailyCup(_cup); } function isSwapStarted() external view returns (bool) { // will it save gas if I do 2x if?? return block.timestamp >= swapStartsOn || swapData.swapEnabledAt != 0; } function canSwapTokens(address _address) external view returns (bool) { uint256 balance = balanceOf(_address); if (balance == 0) return false; (uint256 limit,) = _currentLimit(swapData); return balance / ONE <= limit; } function currentLimit() external view returns (uint256 limit) { (limit,) = _currentLimit(swapData); limit *= ONE; } function _currentLimit(SwapData memory data) internal view returns (uint256 limit, bool fullLimit) { if (block.timestamp < swapStartsOn && data.swapEnabledAt == 0) return (0, false); fullLimit = block.timestamp - data.dailyCupTimestamp >= 24 hours; limit = fullLimit ? data.dailyCup : data.dailyCup - data.usedLimit; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract Owned is Ownable { constructor(address _owner) { transferOwnership(_owner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/Owned.sol"; import "../interfaces/IBurnableToken.sol"; /// @author umb.network abstract contract MintableToken is Owned, ERC20, IBurnableToken { uint256 public immutable maxAllowedTotalSupply; uint256 public everMinted; modifier assertMaxSupply(uint256 _amountToMint) { _assertMaxSupply(_amountToMint); _; } // ========== CONSTRUCTOR ========== // constructor (uint256 _maxAllowedTotalSupply) { require(_maxAllowedTotalSupply != 0, "_maxAllowedTotalSupply is empty"); maxAllowedTotalSupply = _maxAllowedTotalSupply; } // ========== MUTATIVE FUNCTIONS ========== // function burn(uint256 _amount) override external { _burn(msg.sender, _amount); } // ========== RESTRICTED FUNCTIONS ========== // function mint(address _holder, uint256 _amount) virtual external onlyOwner() assertMaxSupply(_amount) { require(_amount != 0, "zero amount"); _mint(_holder, _amount); } function _assertMaxSupply(uint256 _amountToMint) internal { uint256 everMintedTotal = everMinted + _amountToMint; everMinted = everMintedTotal; require(everMintedTotal <= maxAllowedTotalSupply, "total supply limit exceeded"); } } // 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 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.7.5; interface ISwapReceiver { function swapMint(address _holder, uint256 _amount) external; }
@notice one of the reasons this method can throw is, when we swap for UMB and somebody stake rUMB1 after that. In that case execution of `swapForUMB()` is required (anyone can execute this method) before proceeding.
function exitAndUnlock(uint256[] calldata _lockIds) external { _withdraw(type(uint256).max, msg.sender, msg.sender); _unlockTokensFor(msg.sender, _lockIds, msg.sender); _getReward(msg.sender, msg.sender); }
14,641,452
[ 1, 476, 434, 326, 14000, 333, 707, 848, 604, 353, 16, 1347, 732, 7720, 364, 587, 7969, 471, 2690, 3432, 384, 911, 436, 2799, 38, 21, 1839, 716, 18, 540, 657, 716, 648, 4588, 434, 1375, 22270, 1290, 2799, 38, 20338, 353, 1931, 261, 2273, 476, 848, 1836, 333, 707, 13, 1865, 11247, 310, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2427, 1876, 7087, 12, 11890, 5034, 8526, 745, 892, 389, 739, 2673, 13, 3903, 288, 203, 3639, 389, 1918, 9446, 12, 723, 12, 11890, 5034, 2934, 1896, 16, 1234, 18, 15330, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 26226, 5157, 1290, 12, 3576, 18, 15330, 16, 389, 739, 2673, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 588, 17631, 1060, 12, 3576, 18, 15330, 16, 1234, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]