file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
// RUN: --emit cfg contract c { // BEGIN-CHECK: c::test function test() public pure returns (int32) { int32 x = 102; // CHECK: return int32 102 return x; } // BEGIN-CHECK: c::add function add() public pure returns (int32) { int32 x = 5; x += 3; // CHECK: return int32 8 return x; } // BEGIN-CHECK: c::power function power() public pure returns (uint32) { uint32 x = 2; x = x**4; // CHECK: return uint32 16 return x; } }
BEGIN-CHECK: c::add CHECK: return int32 8
function add() public pure returns (int32) { int32 x = 5; x += 3; return x; }
1,037,997
[ 1, 16061, 17, 10687, 30, 276, 2866, 1289, 14565, 30, 327, 509, 1578, 1725, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 527, 1435, 1071, 16618, 1135, 261, 474, 1578, 13, 288, 203, 202, 202, 474, 1578, 619, 273, 1381, 31, 203, 202, 202, 92, 1011, 890, 31, 203, 202, 202, 2463, 619, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.5; //solhint-disable-next-line import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./LegalEntityVerification.sol"; /** Features: -> Manufacturer mints a token representing the product. -> Hash of the serial number, zip code of the factory will be included in the Product struct. -> When the product is given to next entity, the transfer function will be called and the ownership will be transfered to the next owner. -> It should be possible to trace the output to its original manifacturer. Time |t=0 -> -> t=t ------------------------------------------------------- Owner|Factory -mints-> A1 -transfer-> A2 -transfer-> A3 //TODO: Redo this part. Origin of A3: Factory then. You can trace the transfers in the contract data. //TODO: Refactor that there may be several factories, add functions corresponding to that. */ /// @title Provenance tracking system for manifactured items using ERC721-tokens. /// @author Deniz Surmeli, Doğukan Türksoy /// @notice Use it only for simulation /// @dev Contract is a ERC721 implementation. contract Provenance is ERC721{ /// @notice The production process is serialized, thus we will use this /// field as a counter. uint256 public serialId = 0; /// @notice The deployer of the contract will be the factory. It's the only entity that can mint. address public factory; /// @notice Observe that we need to store the deployed address in order to call functions from it. address public legalEntityContractAddress; /// @notice For structured information. struct Product{ bytes32 _serialHash; //hash of the serial id. uint256 _manufacturerZipCode; //zip code of the manufacturer. In fact, this is a constant. } /// @notice Emits when tokens are transferred. event TokenTransferred(uint256 tokenId,address from,address to); /// @notice Emits when an owner approves the ownership. event TokenApproved(uint256 tokenId,address tokenOwner); event TokenMinted(uint256 tokenId); mapping(uint256=>Product) products; /// @notice We use this mapping to track the origins of the products. mapping(uint256=>address[]) owners; /// @notice We track that the token is in approval or not. mapping(uint256=>bool) approvalState; /// @notice Only addresses that have been approved by state authority can perform actions. /// @param _address address to be queried. modifier onlyVerifiedAddress(address _address){ LegalEntityVerification friendContract = LegalEntityVerification(legalEntityContractAddress); require(friendContract.isVerified(_address),"Only verified addresses can perform actions."); _; } /// @notice Only tokens that have been minted can perform actions. /// @param _tokenId id of the token. modifier onlyExistentToken(uint256 _tokenId){ require(ownerOf(_tokenId) != address(0),"Only minted tokens can be transferred."); _; } /// @notice Only tokens that in state of approval can perform actions /// @param _tokenId id of the token. modifier onlyNonApprovedToken(uint256 _tokenId){ require(approvalState[_tokenId] == true); _; } /// @notice Only authorized addresses can perform actions. /// @param _address address to be queried. modifier onlyAuthorized(address _address){ require(factory == _address,"Only authorized addreses can perform actions."); _; } /// @notice Only the owner of the token can perform actions. /// @param _tokenId ID of the token to be queried against. /// @param _address In query address. modifier onlyOwner(uint256 _tokenId,address _address){ require(ownerOf(_tokenId) == _address,"Only the owner of the token can perform actions."); _; } /// @notice Only approved tokens can be subject to actions. /// @param _tokenId ID of the token to be queried against. /// @param _address In query address. modifier onlyApprovedToken(uint256 _tokenId,address _address){ require(ownerOf(_tokenId) == _address,"Only the owner of the token can perform actions."); require(approvalState[_tokenId] == false,"You can only perform operations on approved tokens."); _; } /// @notice Constructor of the Provenance system. /// @param name_ name of the contract,factory name. /// @param symbol_ symbol of the contract,factory symbol. /// @param auxAddress Address of the helper contract, LegalEntityVerification. constructor(string memory name_,string memory symbol_,address auxAddress) ERC721(name_,symbol_) { factory = msg.sender; legalEntityContractAddress = auxAddress; } /// @notice Ownership approval function. Observe that we are going a bit offroad from ERC-721 Standard here. /// @param _tokenId Token that will be approved. function approveOwnership(uint256 _tokenId) onlyOwner(_tokenId,msg.sender) onlyNonApprovedToken(_tokenId) public{ owners[_tokenId].push(msg.sender); approvalState[_tokenId] = false; emit TokenApproved(_tokenId,msg.sender); } /// @notice Transfers the token with _tokenId from _from to _to. /// @param _from Address that is transfering. /// @param _to Address to be transfered. /// @param _tokenId ID of the token to be transfered. function transferToken(address _from,address _to, uint256 _tokenId) onlyOwner(_tokenId,_from) onlyApprovedToken(_tokenId,_from) onlyVerifiedAddress(_to) onlyExistentToken(_tokenId) public { require(_to != ownerOf(_tokenId)); _transfer(_from,_to,_tokenId); approvalState[_tokenId] = true; emit TokenTransferred(_tokenId,_from,_to); } /// @notice A manufacturer mints a product. Only authorized addreses can call. /// @dev First mint is directly to the factory. function mintProductToken(uint256 _zipCode) onlyAuthorized(msg.sender) public { //wrap the parameters in a clearer way for code readability. uint256 productId = serialId; uint256 manufacturerZipCode = _zipCode; _safeMint(msg.sender,productId); //mint the token, using the ERC721 implementation. Since the company is the minter,and only company members(see:onlyAuthorized) can call the mint, msg.sender is the first receiver automatically. // build product fields and map it to the corresponding address. products[productId] = Product({ _serialHash : keccak256(abi.encodePacked(productId)), _manufacturerZipCode: manufacturerZipCode }); approvalState[productId] = true; //auto-approve transfer for factory approveOwnership(productId); emit TokenMinted(serialId); // increment the id by one since it's serialized. serialId += 1; } /// @notice Fetch the origin address of the product. /// @param _tokenId Tokenized product data's id for indexing. /// @return address of the origin manufacturer. function getTheOriginAddress(uint256 _tokenId) public view returns(address){ return owners[_tokenId][0]; } /// @notice Gets the factory address.(for testing purposes) /// @return the factory address. function getFactoryAddress() public view returns(address){ return factory; } /// @notice Gets the approval state of the token /// @return the token id function getApprovalState(uint256 _tokenId) public view returns(bool){ return approvalState[_tokenId]; } /// @notice Returns the list of all owners for a token.(for testing purposes) /// @param _tokenId tokenId to be queried. /// @return an array of all owners. function getAllOwners(uint256 _tokenId) public view returns(address[] memory){ return owners[_tokenId]; } }
@notice Ownership approval function. Observe that we are going a bit offroad from ERC-721 Standard here. @param _tokenId Token that will be approved.
function approveOwnership(uint256 _tokenId) onlyOwner(_tokenId,msg.sender) onlyNonApprovedToken(_tokenId) public{ owners[_tokenId].push(msg.sender); approvalState[_tokenId] = false; emit TokenApproved(_tokenId,msg.sender); }
12,700,972
[ 1, 5460, 12565, 23556, 445, 18, 21008, 716, 732, 854, 8554, 279, 2831, 3397, 5975, 628, 4232, 39, 17, 27, 5340, 8263, 2674, 18, 225, 389, 2316, 548, 3155, 716, 903, 506, 20412, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 5460, 12565, 12, 11890, 5034, 389, 2316, 548, 13, 1338, 5541, 24899, 2316, 548, 16, 3576, 18, 15330, 13, 1338, 3989, 31639, 1345, 24899, 2316, 548, 13, 1071, 95, 203, 3639, 25937, 63, 67, 2316, 548, 8009, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 23556, 1119, 63, 67, 2316, 548, 65, 273, 629, 31, 203, 3639, 3626, 3155, 31639, 24899, 2316, 548, 16, 3576, 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 ]
// File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: FANtokensol // contracts/FANToken.sol pragma solidity ^0.8.0; contract FANToken is ERC20 { constructor(uint256 initialSupply) ERC20("FAN", "FAN") { _mint(msg.sender, initialSupply); } }
File: FANtokensol contracts/FANToken.sol
contract FANToken is ERC20 { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; constructor(uint256 initialSupply) ERC20("FAN", "FAN") { _mint(msg.sender, initialSupply); } }
14,769,860
[ 1, 812, 30, 478, 1258, 7860, 355, 20092, 19, 42, 1258, 1345, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 478, 1258, 1345, 353, 4232, 39, 3462, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 565, 3885, 12, 11890, 5034, 2172, 3088, 1283, 13, 4232, 39, 3462, 2932, 42, 1258, 3113, 315, 42, 1258, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2172, 3088, 1283, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
@dev Reads the uint216 at `cdPtr` in calldata.
function readUint216( CalldataPointer cdPtr ) internal pure returns (uint216 value) { assembly ("memory-safe") { value := calldataload(cdPtr) } }
8,451,723
[ 1, 7483, 326, 2254, 22, 2313, 622, 1375, 4315, 5263, 68, 316, 745, 892, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 855, 5487, 22, 2313, 12, 203, 3639, 3049, 892, 4926, 7976, 5263, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 22, 2313, 460, 13, 288, 203, 3639, 19931, 7566, 7858, 17, 4626, 7923, 288, 203, 5411, 460, 519, 745, 72, 3145, 6189, 12, 4315, 5263, 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, -100, -100 ]
./full_match/1/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/ConsiderationEncoder.sol
Write offset to orderHashes.
dstHead.offset(ZoneParameters_orderHashes_head_offset).write(tailOffset);
9,675,920
[ 1, 3067, 1384, 358, 1353, 14455, 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, 3639, 3046, 1414, 18, 3348, 12, 4226, 2402, 67, 1019, 14455, 67, 1978, 67, 3348, 2934, 2626, 12, 13101, 2335, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; import "./Ownable.sol"; contract Voting is Ownable { struct Voter { bool isRegistered; bool hasVoted; uint proposalsCount; uint votedProposalId; } struct Proposal { string description; uint voteCount; } enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } address[] public whitelist; Proposal[] public proposals; uint public winningProposalId; mapping (address => Voter) public voters; WorkflowStatus public voteStatus; event VoterRegistered(address voterAddress); event ProposalsRegistrationStarted(); event ProposalsRegistrationEnded(); event ProposalRegistered(uint proposalId); event VotingSessionStarted(); event Voted (address voter, uint proposalId); event VotingSessionEnded(); event VotesTallied(); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); /** @dev Return a list with all allowed address */ function getWhitelist() external view returns(address[] memory) { return whitelist; } /** @dev Return a list of proposals */ function getProposals() external view returns(Proposal[] memory) { return proposals; } /** @dev The administrator registers a voters of voters identified by their Ethereum address. * @param _address voter's ethereum address. * ER1 : The vote has already started. * ER2 : The voter already exist. */ function addToWhitelist(address _address) external onlyOwner { require(voteStatus == WorkflowStatus.RegisteringVoters, "ER1"); require(!voters[_address].isRegistered, "ER2"); voters[_address].isRegistered = true; whitelist.push(_address); emit VoterRegistered(_address); } /** @dev The administrator starts the proposal registration session. * ER1 : The vote has already started. */ function proposalsRegistrationStart() external onlyOwner { require(voteStatus == WorkflowStatus.RegisteringVoters, "ER1"); voteStatus = WorkflowStatus.ProposalsRegistrationStarted; emit ProposalsRegistrationStarted(); emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted); } /** @dev Registered voters are allowed to register their proposals while the registration session is active. * @param _description Content of the proposal. * ER3 : You're not allowed to vote. * ER4 : Registration has not yet started or is already ended. * ER5 : The number of proposals per voter is limited to 100. */ function proposalsRegistration(string memory _description) external { require(voters[msg.sender].isRegistered, "ER3"); require(voteStatus == WorkflowStatus.ProposalsRegistrationStarted, "ER4"); require(voters[msg.sender].proposalsCount <= 99, "ER5"); voters[msg.sender].proposalsCount ++; proposals.push(Proposal(_description, 0)); emit ProposalRegistered(proposals.length-1); } /** @dev The administrator closes the proposal registration session. * ER6 : Registration has to be started */ function proposalsRegistrationEnd() external onlyOwner { require(voteStatus == WorkflowStatus.ProposalsRegistrationStarted, "ER6"); voteStatus = WorkflowStatus.ProposalsRegistrationEnded; emit ProposalsRegistrationEnded(); emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded); } /** @dev Administrator starts the voting session. * ER7 : Registration has to be ended. */ function votingSessionStart() external onlyOwner { require(voteStatus == WorkflowStatus.ProposalsRegistrationEnded, "ER7"); voteStatus = WorkflowStatus.VotingSessionStarted; emit VotingSessionStarted(); emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted); } /** @dev Registered voters vote for their preferred proposals. * @param proposalId Number of the voter's preferred proposal. * ER3 : You're not allowed to vote. * ER8 : You have already voted. * ER9 : Non-existent proposal. * ER10 : The voting session has to be started. */ function vote(uint proposalId) external { require(voters[msg.sender].isRegistered, "ER3"); require(!voters[msg.sender].hasVoted, "ER8"); require(proposalId <= proposals.length - 1, "ER9"); require(voteStatus == WorkflowStatus.VotingSessionStarted, "ER10"); voters[msg.sender].hasVoted = true; voters[msg.sender].votedProposalId = proposalId; proposals[proposalId].voteCount ++; // Other method to count the vote // if (proposals[proposalId].voteCount > proposals[winningProposalId].voteCount) { // winningProposalId = proposalId; // } emit Voted(msg.sender, proposalId); } /** @dev The administrator ends the voting session. * ER10 : The voting session has to be started. */ function votingSessionEnd() external onlyOwner { require(voteStatus == WorkflowStatus.VotingSessionStarted, "ER10"); voteStatus = WorkflowStatus.VotingSessionEnded; emit VotingSessionEnded(); emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted , WorkflowStatus.VotingSessionEnded); } /** @dev The administrator counts the votes. * ER11 : The voting session has to be ended. */ function votesTally() external onlyOwner { require(voteStatus == WorkflowStatus.VotingSessionEnded, "ER11"); uint _count; uint _tempWinner; for (uint i = 0; i < proposals.length; i++) { if (proposals[i].voteCount > _count) { _count = proposals[i].voteCount; _tempWinner = i; } } winningProposalId = _tempWinner; voteStatus = WorkflowStatus.VotesTallied; emit VotesTallied(); emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded , WorkflowStatus.VotesTallied); } }
* @dev Registered voters vote for their preferred proposals. @param proposalId Number of the voter's preferred proposal. ER3 : You're not allowed to vote. ER8 : You have already voted. ER9 : Non-existent proposal. ER10 : The voting session has to be started./ Other method to count the vote if (proposals[proposalId].voteCount > proposals[winningProposalId].voteCount) { winningProposalId = proposalId; }
function vote(uint proposalId) external { require(voters[msg.sender].isRegistered, "ER3"); require(!voters[msg.sender].hasVoted, "ER8"); require(proposalId <= proposals.length - 1, "ER9"); require(voteStatus == WorkflowStatus.VotingSessionStarted, "ER10"); voters[msg.sender].hasVoted = true; voters[msg.sender].votedProposalId = proposalId; proposals[proposalId].voteCount ++; emit Voted(msg.sender, proposalId); }
2,518,683
[ 1, 10868, 331, 352, 414, 12501, 364, 3675, 9119, 450, 22536, 18, 282, 14708, 548, 3588, 434, 326, 331, 20005, 1807, 9119, 14708, 18, 225, 4232, 23, 294, 4554, 4565, 486, 2935, 358, 12501, 18, 225, 4232, 28, 294, 4554, 1240, 1818, 331, 16474, 18, 225, 4232, 29, 294, 3858, 17, 19041, 14708, 18, 225, 4232, 2163, 294, 1021, 331, 17128, 1339, 711, 358, 506, 5746, 18, 19, 4673, 707, 358, 1056, 326, 12501, 309, 261, 685, 22536, 63, 685, 8016, 548, 8009, 25911, 1380, 405, 450, 22536, 63, 8082, 2093, 14592, 548, 8009, 25911, 1380, 13, 288, 377, 5657, 2093, 14592, 548, 273, 14708, 548, 31, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 12501, 12, 11890, 14708, 548, 13, 3903, 288, 203, 3639, 2583, 12, 90, 352, 414, 63, 3576, 18, 15330, 8009, 291, 10868, 16, 315, 654, 23, 8863, 203, 3639, 2583, 12, 5, 90, 352, 414, 63, 3576, 18, 15330, 8009, 5332, 58, 16474, 16, 315, 654, 28, 8863, 203, 3639, 2583, 12, 685, 8016, 548, 1648, 450, 22536, 18, 2469, 300, 404, 16, 315, 654, 29, 8863, 203, 3639, 2583, 12, 25911, 1482, 422, 11363, 1482, 18, 58, 17128, 2157, 9217, 16, 315, 654, 2163, 8863, 203, 540, 203, 3639, 331, 352, 414, 63, 3576, 18, 15330, 8009, 5332, 58, 16474, 273, 638, 31, 203, 3639, 331, 352, 414, 63, 3576, 18, 15330, 8009, 90, 16474, 14592, 548, 273, 14708, 548, 31, 203, 3639, 450, 22536, 63, 685, 8016, 548, 8009, 25911, 1380, 965, 31, 203, 540, 203, 540, 203, 3639, 3626, 776, 16474, 12, 3576, 18, 15330, 16, 14708, 548, 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 ]
pragma solidity ^0.4.18; pragma solidity ^0.4.18; /** * @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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic contracts * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer contracts 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 Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of contracts to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } } /** * @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 contracts * * @dev Implementation of the basic standard contracts. * @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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract PAXToken is BurnableToken, PausableToken { using SafeMath for uint; string public constant name = "Pax Token"; string public constant symbol = "PAX"; uint32 public constant decimals = 10; uint256 public constant INITIAL_SUPPLY = 999500000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. * @param _company address reserve tokens (300000000) * @param _founders_1 address reserve tokens (300000000) * @param _founders_2 address reserve tokens (50000000) * @param _isPause bool (pause === true) */ function PAXToken(address _company, address _founders_1, address _founders_2, bool _isPause) public { require(_company != address(0) && _founders_1 != address(0) && _founders_2 != address(0)); paused = _isPause; totalSupply = INITIAL_SUPPLY; balances[msg.sender] = 349500000 * (10 ** uint256(decimals)); balances[_company] = 300000000 * (10 ** uint256(decimals)); balances[_founders_1] = 300000000 * (10 ** uint256(decimals)); balances[_founders_2] = 50000000 * (10 ** uint256(decimals)); emit Transfer(0x0, msg.sender, balances[msg.sender]); emit Transfer(0x0, _company, balances[_company]); emit Transfer(0x0, _founders_1, balances[_founders_1]); emit Transfer(0x0, _founders_2, balances[_founders_2]); } /** * @dev transfer contracts for a specified address, despite the pause state * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function ownersTransfer(address _to, uint256 _value) public onlyOwner returns (bool) { return BasicToken.transfer(_to, _value); } } contract Crowdsale is Pausable { struct stageInfo { uint start; uint stop; uint duration; uint bonus; uint limit; } /** * @dev Mapping with stageId = stageInfo */ mapping (uint => stageInfo) public stages; /** * @dev Mapping with adress = with balance */ mapping(address => uint) public balances; /** * @dev Softcap */ uint public constant softcap = 2500 ether; /** * @dev xDecimals */ uint public constant decimals = 1E10; /** * @dev ICO Period Number */ uint public period = 5; /** * @dev Total number of minted tokens */ uint public hardcap; /** * @dev Cost of the token */ uint public rate; /** * @dev Number of sold tokens */ uint public totalSold = 0; /** * @dev Assembled Eth */ uint256 public sumWei; /** * @dev ICO Status */ bool public state; /** * @dev Once call flag */ bool public requireOnce = true; /** * @dev Once burning flag */ bool public isBurned; /** * @dev Reserve tokens adress for company (300000000) */ address public company; /** * @dev Reserve tokens adress for founders first (300000000) */ address public founders_1; /** * @dev Reserve tokens adress for founders second (50000000) */ address public founders_2; /** * @dev The address to which the received ether will be sent */ address public multisig; /** * @dev Tokens classes */ PAXToken public token; /** * @dev Number of coins for the typical period */ uint private constant typicalBonus = 100; /** * @dev Sending tokens */ uint private sendingTokens; /** * @dev Time left */ uint private timeLeft; /** * @dev Pause date */ uint private pauseDate; /** * @dev Paused by value flag */ bool private pausedByValue; /** * @dev Manual pause flag */ bool private manualPause; event StartICO(); event StopICO(); event BurnUnsoldTokens(); event NewWalletAddress(address _to); event Refund(address _wallet, uint _val); event DateMoved(uint value); using SafeMath for uint; modifier saleIsOn() { require(state); uint stageId = getStageId(); if (period != stageId || stageId == 5) { usersPause(); (msg.sender).transfer(msg.value); } else _; } modifier isUnderHardCap() { uint tokenBalance = token.balanceOf(this); require( tokenBalance <= hardcap && tokenBalance >= 500 ); _; } function Crowdsale(address _company, address _founders_1, address _founders_2, address _token) public { multisig = owner; rate = (uint)(1 ether).div(5000); stages[0] = stageInfo({ start: 0, stop: 0, duration: 14 days, bonus: 130, limit: 44500000 * decimals }); stages[1] = stageInfo({ start: 0, stop: 0, duration: 14 days, bonus: 115, limit: 85000000 * decimals }); stages[2] = stageInfo({ start: 0, stop: 0, duration: 14 days, bonus: 110, limit: 100000000 * decimals }); stages[3] = stageInfo({ start: 0, stop: 0, duration: 14 days, bonus: 105, limit: 120000000 * decimals }); hardcap = 349500000 * decimals; token = PAXToken(_token); company = _company; founders_1 = _founders_1; founders_2 = _founders_2; } /** * @dev Fallback function */ function() whenNotPaused saleIsOn external payable { require (msg.value > 0); sendTokens(msg.value, msg.sender); } /** * @dev Manual sending tokens * @param _to address where sending tokens * @param _value uint256 value tokens for sending */ function manualSendTokens(address _to, uint256 _value) public onlyOwner returns(bool) { uint tokens = _value; uint avalibleTokens = token.balanceOf(this); if (tokens < avalibleTokens) { if (tokens <= stages[3].limit) { stages[3].limit = (stages[3].limit).sub(tokens); } else if (tokens <= (stages[3].limit).add(stages[2].limit)) { stages[2].limit = (stages[2].limit).sub(tokens.sub(stages[3].limit)); stages[3].limit = 0; } else if (tokens <= (stages[3].limit).add(stages[2].limit).add(stages[1].limit)) { stages[1].limit = (stages[1].limit).sub(tokens.sub(stages[3].limit).sub(stages[2].limit)); stages[3].limit = 0; stages[2].limit = 0; } else if (tokens <= (stages[3].limit).add(stages[2].limit).add(stages[1].limit).add(stages[0].limit)) { stages[0].limit = (stages[0].limit).sub(tokens.sub(stages[3].limit).sub(stages[2].limit).sub(stages[1].limit)); stages[3].limit = 0; stages[2].limit = 0; stages[1].limit = 0; } } else { tokens = avalibleTokens; stages[3].limit = 0; stages[2].limit = 0; stages[1].limit = 0; stages[0].limit = 0; } sendingTokens = sendingTokens.add(tokens); sumWei = sumWei.add(tokens.mul(rate).div(decimals)); totalSold = totalSold.add(tokens); token.ownersTransfer(_to, tokens); return true; } /** * @dev Return Etherium all investors */ function refund() public { require(sumWei < softcap && !state); uint value = balances[msg.sender]; balances[msg.sender] = 0; emit Refund(msg.sender, value); msg.sender.transfer(value); } /** * @dev Burning all tokens on mintAddress */ function burnUnsoldTokens() onlyOwner public returns(bool) { require(!state); require(!isBurned); isBurned = true; emit BurnUnsoldTokens(); token.burn(token.balanceOf(this)); if (token.paused()) { token.unpause(); } return true; } /** * @dev Starting ICO */ function startICO() public onlyOwner returns(bool) { require(stages[0].start >= now); require(requireOnce); requireOnce = false; state = true; period = 0; emit StartICO(); token.ownersTransfer(company, (uint)(300000000).mul(decimals)); token.ownersTransfer(founders_1, (uint)(300000000).mul(decimals)); token.ownersTransfer(founders_2, (uint)(50000000).mul(decimals)); return true; } /** * @dev Turning off the ICO */ function stopICO() onlyOwner public returns(bool) { state = false; emit StopICO(); if (token.paused()) { token.unpause(); } return true; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { manualPause = true; usersPause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { uint shift = now.sub(pauseDate); dateMove(shift); period = getStageId(); pausedByValue = false; manualPause = false; super.unpause(); } /** * @dev Withdrawal Etherium from smart-contract */ function withDrawal() public onlyOwner { if(!state && sumWei >= softcap) { multisig.transfer(address(this).balance); } } /** * @dev Returns stage id */ function getStageId() public view returns(uint) { uint stageId; uint today = now; if (today < stages[0].stop) { stageId = 0; } else if (today >= stages[1].start && today < stages[1].stop ) { stageId = 1; } else if (today >= stages[2].start && today < stages[2].stop ) { stageId = 2; } else if (today >= stages[3].start && today < stages[3].stop ) { stageId = 3; } else if (today >= stages[3].stop) { stageId = 4; } else { return 5; } uint tempId = (stageId > period) ? stageId : period; return tempId; } /** * @dev Returns Limit of coins for the period and Number of coins taking * into account the bonus for the period */ function getStageData() public view returns(uint tempLimit, uint tempBonus) { uint stageId = getStageId(); tempBonus = stages[stageId].bonus; if (stageId == 0) { tempLimit = stages[0].limit; } else if (stageId == 1) { tempLimit = (stages[0].limit).add(stages[1].limit); } else if (stageId == 2) { tempLimit = (stages[0].limit).add(stages[1].limit).add(stages[2].limit); } else if (stageId == 3) { tempLimit = (stages[0].limit).add(stages[1].limit).add(stages[2].limit).add(stages[3].limit); } else { tempLimit = token.balanceOf(this); tempBonus = typicalBonus; return; } tempLimit = tempLimit.sub(totalSold); return; } /** * @dev Returns the amount for which you can redeem all tokens for the current period */ function calculateStagePrice() public view returns(uint price) { uint limit; uint bonusCoefficient; (limit, bonusCoefficient) = getStageData(); price = limit.mul(rate).mul(100).div(bonusCoefficient).div(decimals); } /** * @dev Sending tokens to the recipient, based on the amount of ether that it sent * @param _etherValue uint Amount of sent ether * @param _to address The address which you want to transfer to */ function sendTokens(uint _etherValue, address _to) internal isUnderHardCap { uint limit; uint bonusCoefficient; (limit, bonusCoefficient) = getStageData(); uint tokens = (_etherValue).mul(bonusCoefficient).mul(decimals).div(100); tokens = tokens.div(rate); bool needPause; if (tokens > limit) { needPause = true; uint stageEther = calculateStagePrice(); period++; if (period == 4) { balances[msg.sender] = balances[msg.sender].add(stageEther); sumWei = sumWei.add(stageEther); token.ownersTransfer(_to, limit); totalSold = totalSold.add(limit); _to.transfer(_etherValue.sub(stageEther)); state = false; return; } balances[msg.sender] = balances[msg.sender].add(stageEther); sumWei = sumWei.add(stageEther); token.ownersTransfer(_to, limit); totalSold = totalSold.add(limit); sendTokens(_etherValue.sub(stageEther), _to); } else { require(tokens <= token.balanceOf(this)); if (limit.sub(tokens) < 500) { needPause = true; period++; } balances[msg.sender] = balances[msg.sender].add(_etherValue); sumWei = sumWei.add(_etherValue); token.ownersTransfer(_to, tokens); totalSold = totalSold.add(tokens); } if (needPause) { pausedByValue = true; usersPause(); } } /** * @dev called by the contract to pause, triggers stopped state */ function usersPause() private { pauseDate = now; paused = true; emit Pause(); } /** * @dev Moving date after the pause * @param _shift uint Time in seconds */ function dateMove(uint _shift) private returns(bool) { require(_shift > 0); uint i; if (pausedByValue) { stages[period].start = now; stages[period].stop = (stages[period].start).add(stages[period].duration); for (i = period + 1; i < 4; i++) { stages[i].start = stages[i - 1].stop; stages[i].stop = (stages[i].start).add(stages[i].duration); } } else { if (manualPause) stages[period].stop = (stages[period].stop).add(_shift); for (i = period + 1; i < 4; i++) { stages[i].start = (stages[i].start).add(_shift); stages[i].stop = (stages[i].stop).add(_shift); } } emit DateMoved(_shift); return true; } /** * @dev Returns the total number of tokens available for sale */ function tokensAmount() public view returns(uint) { return token.balanceOf(this); } /** * @dev Returns number of supplied tokens */ function tokensSupply() public view returns(uint) { return token.totalSupply(); } /** * @dev Set start date * @param _start uint Time start */ function setStartDate(uint _start) public onlyOwner returns(bool) { require(_start > now); require(requireOnce); stages[0].start = _start; stages[0].stop = _start.add(stages[0].duration); stages[1].start = stages[0].stop; stages[1].stop = stages[1].start.add(stages[1].duration); stages[2].start = stages[1].stop; stages[2].stop = stages[2].start.add(stages[2].duration); stages[3].start = stages[2].stop; stages[3].stop = stages[3].start.add(stages[3].duration); return true; } /** * @dev Sets new multisig address to which the received ether will be sent * @param _to address */ function setMultisig(address _to) public onlyOwner returns(bool) { require(_to != address(0)); multisig = _to; emit NewWalletAddress(_to); return true; } /** * @dev Change first adress with reserve(300000000 tokens) * @param _company address */ function setReserveForCompany(address _company) public onlyOwner { require(_company != address(0)); require(requireOnce); company = _company; } /** * @dev Change second adress with reserve(300000000 tokens) * @param _founders_1 address */ function setReserveForFoundersFirst(address _founders_1) public onlyOwner { require(_founders_1 != address(0)); require(requireOnce); founders_1 = _founders_1; } /** * @dev Change third adress with reserve(50000000 tokens) * @param _founders_2 address */ function setReserveForFoundersSecond(address _founders_2) public onlyOwner { require(_founders_2 != address(0)); require(requireOnce); founders_2 = _founders_2; } }
* @dev Number of coins for the typical period/
uint private constant typicalBonus = 100;
13,057,154
[ 1, 1854, 434, 276, 9896, 364, 326, 24917, 3879, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 3238, 5381, 24917, 38, 22889, 273, 2130, 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 ]
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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.21; /// @title Utility Functions for uint8 /// @author Kongliang Zhong - <<span class="__cf_email__" data-cfemail="cba0a4a5aca7a2aaa5ac8ba7a4a4bbb9a2a5ace5a4b9ac">[email&#160;protected]</span>>, /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="1074717e79757c507c7f7f6062797e773e7f6277">[email&#160;protected]</span>>. library MathUint8 { function xorReduce( uint8[] arr, uint len ) internal pure returns (uint8 res) { res = arr[0]; for (uint i = 1; i < len; i++) { res ^= arr[i]; } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title Utility Functions for uint /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="1d797c737478715d7172726d6f74737a33726f7a">[email&#160;protected]</span>> library MathUint { function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function tolerantSub(uint a, uint b) internal pure returns (uint c) { return (a >= b) ? a - b : 0; } /// @dev calculate the square of Coefficient of Variation (CV) /// https://en.wikipedia.org/wiki/Coefficient_of_variation function cvsquare( uint[] arr, uint scale ) internal pure returns (uint) { uint len = arr.length; require(len > 1); require(scale > 0); uint avg = 0; for (uint i = 0; i < len; i++) { avg += arr[i]; } avg = avg / len; if (avg == 0) { return 0; } uint cvs = 0; uint s; uint item; for (i = 0; i < len; i++) { item = arr[i]; s = item > avg ? item - avg : avg - item; cvs += mul(s, s); } return ((mul(mul(cvs, scale), scale) / avg) / avg) / (len - 1); } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title Utility Functions for byte32 /// @author Kongliang Zhong - <<span class="__cf_email__" data-cfemail="c6ada9a8a1aaafa7a8a186aaa9a9b6b4afa8a1e8a9b4a1">[email&#160;protected]</span>>, /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="7014111e19151c301c1f1f0002191e175e1f0217">[email&#160;protected]</span>>. library MathBytes32 { function xorReduce( bytes32[] arr, uint len ) internal pure returns (bytes32 res) { res = arr[0]; for (uint i = 1; i < len; i++) { res ^= arr[i]; } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title Utility Functions for address /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="fb9f9a95929e97bb9794948b8992959cd594899c">[email&#160;protected]</span>> library AddressUtil { function isContract(address addr) internal view returns (bool) { if (addr == 0x0) { return false; } else { uint size; assembly { size := extcodesize(addr) } return size > 0; } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title ERC20 Token Interface /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="eb8f8a85828e87ab8784849b9982858cc584998c">[email&#160;protected]</span>> contract ERC20 { function balanceOf(address who) view public returns (uint256); function allowance(address owner, address spender) view public returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title Loopring Token Exchange Protocol Contract Interface /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="690d0807000c0529050606191b00070e47061b0e">[email&#160;protected]</span>> /// @author Kongliang Zhong - <<span class="__cf_email__" data-cfemail="b3d8dcddd4dfdad2ddd4f3dfdcdcc3c1daddd49ddcc1d4">[email&#160;protected]</span>> contract LoopringProtocol { //////////////////////////////////////////////////////////////////////////// /// Constants /// //////////////////////////////////////////////////////////////////////////// uint8 public constant MARGIN_SPLIT_PERCENTAGE_BASE = 100; //////////////////////////////////////////////////////////////////////////// /// Events /// //////////////////////////////////////////////////////////////////////////// /// @dev Event to emit if a ring is successfully mined. /// _amountsList is an array of: /// [_amountS, _amountB, _lrcReward, _lrcFee, splitS, splitB]. event RingMined( uint _ringIndex, bytes32 indexed _ringHash, address _miner, address _feeRecipient, bytes32[] _orderHashList, uint[6][] _amountsList ); event OrderCancelled( bytes32 indexed _orderHash, uint _amountCancelled ); event AllOrdersCancelled( address indexed _address, uint _cutoff ); event OrdersCancelled( address indexed _address, address _token1, address _token2, uint _cutoff ); //////////////////////////////////////////////////////////////////////////// /// Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Cancel a order. cancel amount(amountS or amountB) can be specified /// in orderValues. /// @param addresses owner, tokenS, tokenB, authAddr /// @param orderValues amountS, amountB, validSince (second), /// validUntil (second), lrcFee, walletId, and /// cancelAmount. /// @param buyNoMoreThanAmountB - /// This indicates when a order should be considered /// as &#39;completely filled&#39;. /// @param marginSplitPercentage - /// Percentage of margin split to share with miner. /// @param v Order ECDSA signature parameter v. /// @param r Order ECDSA signature parameters r. /// @param s Order ECDSA signature parameters s. function cancelOrder( address[4] addresses, uint[7] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) external; /// @dev Set a cutoff timestamp to invalidate all orders whose timestamp /// is smaller than or equal to the new value of the address&#39;s cutoff /// timestamp, for a specific trading pair. /// @param cutoff The cutoff timestamp, will default to `block.timestamp` /// if it is 0. function cancelAllOrdersByTradingPair( address token1, address token2, uint cutoff ) external; /// @dev Set a cutoff timestamp to invalidate all orders whose timestamp /// is smaller than or equal to the new value of the address&#39;s cutoff /// timestamp. /// @param cutoff The cutoff timestamp, will default to `block.timestamp` /// if it is 0. function cancelAllOrders(uint cutoff) external; /// @dev Submit a order-ring for validation and settlement. /// @param addressList List of each order&#39;s owner, tokenS, and authAddr. /// Note that next order&#39;s `tokenS` equals this order&#39;s /// `tokenB`. /// @param uintArgsList List of uint-type arguments in this order: /// amountS, amountB, validSince (second), /// validUntil (second), lrcFee, rateAmountS, and walletId. /// @param uint8ArgsList - /// List of unit8-type arguments, in this order: /// marginSplitPercentageList. /// @param buyNoMoreThanAmountBList - /// This indicates when a order should be considered /// @param vList List of v for each order. This list is 1-larger than /// the previous lists, with the last element being the /// v value of the ring signature. /// @param rList List of r for each order. This list is 1-larger than /// the previous lists, with the last element being the /// r value of the ring signature. /// @param sList List of s for each order. This list is 1-larger than /// the previous lists, with the last element being the /// s value of the ring signature. /// @param minerId The address pair that miner registered in NameRegistry. /// The address pair contains a signer address and a fee /// recipient address. /// The signer address is used for sign this tx. /// The Recipient address for fee collection. If this is /// &#39;0x0&#39;, all fees will be paid to the address who had /// signed this transaction, not `msg.sender`. Noted if /// LRC need to be paid back to order owner as the result /// of fee selection model, LRC will also be sent from /// this address. /// @param feeSelections - /// Bits to indicate fee selections. `1` represents margin /// split and `0` represents LRC as fee. function submitRing( address[3][] addressList, uint[7][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, uint minerId, uint16 feeSelections ) public; } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title Ethereum Address Register Contract /// @dev This contract maintains a name service for addresses and miner. /// @author Kongliang Zhong - <<span class="__cf_email__" data-cfemail="12797d7c757e7b737c75527e7d7d62607b7c753c7d6075">[email&#160;protected]</span>>, /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="88ece9e6e1ede4c8e4e7e7f8fae1e6efa6e7faef">[email&#160;protected]</span>>, contract NameRegistry { uint public nextId = 0; mapping (uint => Participant) public participantMap; mapping (address => NameInfo) public nameInfoMap; mapping (bytes12 => address) public ownerMap; mapping (address => string) public nameMap; struct NameInfo { bytes12 name; uint[] participantIds; } struct Participant { address feeRecipient; address signer; bytes12 name; address owner; } event NameRegistered ( string name, address indexed owner ); event NameUnregistered ( string name, address indexed owner ); event OwnershipTransfered ( bytes12 name, address oldOwner, address newOwner ); event ParticipantRegistered ( bytes12 name, address indexed owner, uint indexed participantId, address singer, address feeRecipient ); event ParticipantUnregistered ( uint participantId, address owner ); function registerName(string name) external { require(isNameValid(name)); bytes12 nameBytes = stringToBytes12(name); require(ownerMap[nameBytes] == 0x0); require(stringToBytes12(nameMap[msg.sender]) == bytes12(0x0)); nameInfoMap[msg.sender] = NameInfo(nameBytes, new uint[](0)); ownerMap[nameBytes] = msg.sender; nameMap[msg.sender] = name; emit NameRegistered(name, msg.sender); } function unregisterName(string name) external { NameInfo storage nameInfo = nameInfoMap[msg.sender]; uint[] storage participantIds = nameInfo.participantIds; bytes12 nameBytes = stringToBytes12(name); require(nameInfo.name == nameBytes); for (uint i = 0; i < participantIds.length; i++) { delete participantMap[participantIds[i]]; } delete nameInfoMap[msg.sender]; delete nameMap[msg.sender]; delete ownerMap[nameBytes]; emit NameUnregistered(name, msg.sender); } function transferOwnership(address newOwner) external { require(newOwner != 0x0); require(nameInfoMap[newOwner].name.length == 0); NameInfo storage nameInfo = nameInfoMap[msg.sender]; string storage name = nameMap[msg.sender]; uint[] memory participantIds = nameInfo.participantIds; for (uint i = 0; i < participantIds.length; i ++) { Participant storage p = participantMap[participantIds[i]]; p.owner = newOwner; } delete nameInfoMap[msg.sender]; delete nameMap[msg.sender]; nameInfoMap[newOwner] = nameInfo; nameMap[newOwner] = name; emit OwnershipTransfered(nameInfo.name, msg.sender, newOwner); } /* function addParticipant(address feeRecipient) */ /* external */ /* returns (uint) */ /* { */ /* return addParticipant(feeRecipient, feeRecipient); */ /* } */ function addParticipant( address feeRecipient, address singer ) external returns (uint) { require(feeRecipient != 0x0 && singer != 0x0); NameInfo storage nameInfo = nameInfoMap[msg.sender]; bytes12 name = nameInfo.name; require(name.length > 0); Participant memory participant = Participant( feeRecipient, singer, name, msg.sender ); uint participantId = ++nextId; participantMap[participantId] = participant; nameInfo.participantIds.push(participantId); emit ParticipantRegistered( name, msg.sender, participantId, singer, feeRecipient ); return participantId; } function removeParticipant(uint participantId) external { require(msg.sender == participantMap[participantId].owner); NameInfo storage nameInfo = nameInfoMap[msg.sender]; uint[] storage participantIds = nameInfo.participantIds; delete participantMap[participantId]; uint len = participantIds.length; for (uint i = 0; i < len; i ++) { if (participantId == participantIds[i]) { participantIds[i] = participantIds[len - 1]; participantIds.length -= 1; } } emit ParticipantUnregistered(participantId, msg.sender); } function getParticipantById(uint id) external view returns (address feeRecipient, address signer) { Participant storage addressSet = participantMap[id]; feeRecipient = addressSet.feeRecipient; signer = addressSet.signer; } function getFeeRecipientById(uint id) external view returns (address feeRecipient) { Participant storage addressSet = participantMap[id]; feeRecipient = addressSet.feeRecipient; } function getParticipantIds(string name, uint start, uint count) external view returns (uint[] idList) { bytes12 nameBytes = stringToBytes12(name); address owner = ownerMap[nameBytes]; require(owner != 0x0); NameInfo storage nameInfo = nameInfoMap[owner]; uint[] storage pIds = nameInfo.participantIds; uint len = pIds.length; if (start >= len) { return; } uint end = start + count; if (end > len) { end = len; } if (start == end) { return; } idList = new uint[](end - start); for (uint i = start; i < end; i ++) { idList[i - start] = pIds[i]; } } function getOwner(string name) external view returns (address) { bytes12 nameBytes = stringToBytes12(name); return ownerMap[nameBytes]; } function isNameValid(string name) internal pure returns (bool) { bytes memory temp = bytes(name); return temp.length >= 6 && temp.length <= 12; } function stringToBytes12(string str) internal pure returns (bytes12 result) { assembly { result := mload(add(str, 32)) } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @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. function Ownable() public { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } /// @dev Allows the current owner to transfer control of the contract to a /// newOwner. /// @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) onlyOwner public { require(newOwner != 0x0); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title Claimable /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) onlyOwner public { require(newOwner != 0x0 && newOwner != owner); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = 0x0; } } /// @title Token Register Contract /// @dev This contract maintains a list of tokens the Protocol supports. /// @author Kongliang Zhong - <<span class="__cf_email__" data-cfemail="91fafefff6fdf8f0fff6d1fdfefee1e3f8fff6bffee3f6">[email&#160;protected]</span>>, /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="c3a7a2adaaa6af83afacacb3b1aaada4edacb1a4">[email&#160;protected]</span>>. contract TokenRegistry is Claimable { using AddressUtil for address; address tokenMintAddr; address[] public addresses; mapping (address => TokenInfo) addressMap; mapping (string => address) symbolMap; //////////////////////////////////////////////////////////////////////////// /// Structs /// //////////////////////////////////////////////////////////////////////////// struct TokenInfo { uint pos; // 0 mens unregistered; if > 0, pos + 1 is the // token&#39;s position in `addresses`. string symbol; // Symbol of the token } //////////////////////////////////////////////////////////////////////////// /// Events /// //////////////////////////////////////////////////////////////////////////// event TokenRegistered(address addr, string symbol); event TokenUnregistered(address addr, string symbol); //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Disable default function. function () payable public { revert(); } function TokenRegistry(address _tokenMintAddr) public { require(_tokenMintAddr.isContract()); tokenMintAddr = _tokenMintAddr; } function registerToken( address addr, string symbol ) external onlyOwner { registerTokenInternal(addr, symbol); } function registerMintedToken( address addr, string symbol ) external { require(msg.sender == tokenMintAddr); registerTokenInternal(addr, symbol); } function unregisterToken( address addr, string symbol ) external onlyOwner { require(addr != 0x0); require(symbolMap[symbol] == addr); delete symbolMap[symbol]; uint pos = addressMap[addr].pos; require(pos != 0); delete addressMap[addr]; // We will replace the token we need to unregister with the last token // Only the pos of the last token will need to be updated address lastToken = addresses[addresses.length - 1]; // Don&#39;t do anything if the last token is the one we want to delete if (addr != lastToken) { // Swap with the last token and update the pos addresses[pos - 1] = lastToken; addressMap[lastToken].pos = pos; } addresses.length--; emit TokenUnregistered(addr, symbol); } function areAllTokensRegistered(address[] addressList) external view returns (bool) { for (uint i = 0; i < addressList.length; i++) { if (addressMap[addressList[i]].pos == 0) { return false; } } return true; } function getAddressBySymbol(string symbol) external view returns (address) { return symbolMap[symbol]; } function isTokenRegisteredBySymbol(string symbol) public view returns (bool) { return symbolMap[symbol] != 0x0; } function isTokenRegistered(address addr) public view returns (bool) { return addressMap[addr].pos != 0; } function getTokens( uint start, uint count ) public view returns (address[] addressList) { uint num = addresses.length; if (start >= num) { return; } uint end = start + count; if (end > num) { end = num; } if (start == num) { return; } addressList = new address[](end - start); for (uint i = start; i < end; i++) { addressList[i - start] = addresses[i]; } } function registerTokenInternal( address addr, string symbol ) internal { require(0x0 != addr); require(bytes(symbol).length > 0); require(0x0 == symbolMap[symbol]); require(0 == addressMap[addr].pos); addresses.push(addr); symbolMap[symbol] = addr; addressMap[addr] = TokenInfo(addresses.length, symbol); emit TokenRegistered(addr, symbol); } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title TokenTransferDelegate /// @dev Acts as a middle man to transfer ERC20 tokens on behalf of different /// versions of Loopring protocol to avoid ERC20 re-authorization. /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="5b3f3a35323e371b3734342b2932353c7534293c">[email&#160;protected]</span>>. contract TokenTransferDelegate is Claimable { using MathUint for uint; //////////////////////////////////////////////////////////////////////////// /// Variables /// //////////////////////////////////////////////////////////////////////////// mapping(address => AddressInfo) private addressInfos; address public latestAddress; //////////////////////////////////////////////////////////////////////////// /// Structs /// //////////////////////////////////////////////////////////////////////////// struct AddressInfo { address previous; uint32 index; bool authorized; } //////////////////////////////////////////////////////////////////////////// /// Modifiers /// //////////////////////////////////////////////////////////////////////////// modifier onlyAuthorized() { require(addressInfos[msg.sender].authorized); _; } //////////////////////////////////////////////////////////////////////////// /// Events /// //////////////////////////////////////////////////////////////////////////// event AddressAuthorized(address indexed addr, uint32 number); event AddressDeauthorized(address indexed addr, uint32 number); //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Disable default function. function () payable public { revert(); } /// @dev Add a Loopring protocol address. /// @param addr A loopring protocol address. function authorizeAddress(address addr) onlyOwner external { AddressInfo storage addrInfo = addressInfos[addr]; if (addrInfo.index != 0) { // existing if (addrInfo.authorized == false) { // re-authorize addrInfo.authorized = true; emit AddressAuthorized(addr, addrInfo.index); } } else { address prev = latestAddress; if (prev == 0x0) { addrInfo.index = 1; addrInfo.authorized = true; } else { addrInfo.previous = prev; addrInfo.index = addressInfos[prev].index + 1; } addrInfo.authorized = true; latestAddress = addr; emit AddressAuthorized(addr, addrInfo.index); } } /// @dev Remove a Loopring protocol address. /// @param addr A loopring protocol address. function deauthorizeAddress(address addr) onlyOwner external { uint32 index = addressInfos[addr].index; if (index != 0) { addressInfos[addr].authorized = false; emit AddressDeauthorized(addr, index); } } function getLatestAuthorizedAddresses(uint max) external view returns (address[] addresses) { addresses = new address[](max); address addr = latestAddress; AddressInfo memory addrInfo; uint count = 0; while (addr != 0x0 && count < max) { addrInfo = addressInfos[addr]; if (addrInfo.index == 0) { break; } addresses[count++] = addr; addr = addrInfo.previous; } } /// @dev Invoke ERC20 transferFrom method. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. function transferToken( address token, address from, address to, uint value) onlyAuthorized external { if (value > 0 && from != to && to != 0x0) { require( ERC20(token).transferFrom(from, to, value) ); } } function batchTransferToken( address lrcTokenAddress, address minerFeeRecipient, uint8 walletSplitPercentage, bytes32[] batch) onlyAuthorized external { uint len = batch.length; require(len % 7 == 0); require(walletSplitPercentage > 0 && walletSplitPercentage < 100); ERC20 lrc = ERC20(lrcTokenAddress); for (uint i = 0; i < len; i += 7) { address owner = address(batch[i]); address prevOwner = address(batch[(i + len - 7) % len]); // Pay token to previous order, or to miner as previous order&#39;s // margin split or/and this order&#39;s margin split. ERC20 token = ERC20(address(batch[i + 1])); // Here batch[i + 2] has been checked not to be 0. if (owner != prevOwner) { require( token.transferFrom( owner, prevOwner, uint(batch[i + 2]) ) ); } // Miner pays LRx fee to order owner uint lrcReward = uint(batch[i + 4]); if (lrcReward != 0 && minerFeeRecipient != owner) { require( lrc.transferFrom( minerFeeRecipient, owner, lrcReward ) ); } // Split margin-split income between miner and wallet splitPayFee( token, uint(batch[i + 3]), owner, minerFeeRecipient, address(batch[i + 6]), walletSplitPercentage ); // Split LRx fee income between miner and wallet splitPayFee( lrc, uint(batch[i + 5]), owner, minerFeeRecipient, address(batch[i + 6]), walletSplitPercentage ); } } function isAddressAuthorized(address addr) public view returns (bool) { return addressInfos[addr].authorized; } function splitPayFee( ERC20 token, uint fee, address owner, address minerFeeRecipient, address walletFeeRecipient, uint walletSplitPercentage ) internal { if (fee == 0) { return; } uint walletFee = (walletFeeRecipient == 0x0) ? 0 : fee.mul(walletSplitPercentage) / 100; uint minerFee = fee - walletFee; if (walletFee > 0 && walletFeeRecipient != owner) { require( token.transferFrom( owner, walletFeeRecipient, walletFee ) ); } if (minerFee > 0 && minerFeeRecipient != 0x0 && minerFeeRecipient != owner) { require( token.transferFrom( owner, minerFeeRecipient, minerFee ) ); } } } /// @title Loopring Token Exchange Protocol Implementation Contract /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="0a6e6b64636f664a6665657a7863646d2465786d">[email&#160;protected]</span>>, /// @author Kongliang Zhong - <<span class="__cf_email__" data-cfemail="4e2521202922272f20290e2221213e3c27202960213c29">[email&#160;protected]</span>> /// /// Recognized contributing developers from the community: /// https://github.com/Brechtpd /// https://github.com/rainydio /// https://github.com/BenjaminPrice /// https://github.com/jonasshen contract LoopringProtocolImpl is LoopringProtocol { using AddressUtil for address; using MathBytes32 for bytes32[]; using MathUint for uint; using MathUint8 for uint8[]; //////////////////////////////////////////////////////////////////////////// /// Variables /// //////////////////////////////////////////////////////////////////////////// address public lrcTokenAddress = 0xEF68e7C694F40c8202821eDF525dE3782458639f; address public tokenRegistryAddress = 0xaD3407deDc56A1F69389Edc191b770F0c935Ea37; address public delegateAddress = 0x7b126ab811f278f288bf1d62d47334351dA20d1d; address public nameRegistryAddress = 0xC897816C1A6DB4A2923b7D75d9B812e2f62cF504; uint64 public ringIndex = 0; uint8 public walletSplitPercentage = 20; // Exchange rate (rate) is the amount to sell or sold divided by the amount // to buy or bought. // // Rate ratio is the ratio between executed rate and an order&#39;s original // rate. // // To require all orders&#39; rate ratios to have coefficient ofvariation (CV) // smaller than 2.5%, for an example , rateRatioCVSThreshold should be: // `(0.025 * RATE_RATIO_SCALE)^2` or 62500. uint public constant rateRatioCVSThreshold = 62500; uint public constant MAX_RING_SIZE = 16; uint public constant RATE_RATIO_SCALE = 10000; uint64 public constant ENTERED_MASK = 1 << 63; // The following map is used to keep trace of order fill and cancellation // history. mapping (bytes32 => uint) public cancelledOrFilled; // This map is used to keep trace of order&#39;s cancellation history. mapping (bytes32 => uint) public cancelled; // A map from address to its cutoff timestamp. mapping (address => uint) public cutoffs; // A map from address to its trading-pair cutoff timestamp. mapping (address => mapping (bytes20 => uint)) public tradingPairCutoffs; //////////////////////////////////////////////////////////////////////////// /// Structs /// //////////////////////////////////////////////////////////////////////////// struct Rate { uint amountS; uint amountB; } /// @param tokenS Token to sell. /// @param tokenB Token to buy. /// @param amountS Maximum amount of tokenS to sell. /// @param amountB Minimum amount of tokenB to buy if all amountS sold. /// @param authAddr An address to verify miner has access to the order&#39;s /// auth private-key. /// @param validSince Indicating when this order should be treated as /// valid for trading, in second. /// @param validUntil Indicating when this order should be treated as /// expired, in second. /// @param lrcFee Max amount of LRC to pay for miner. The real amount /// to pay is proportional to fill amount. /// @param buyNoMoreThanAmountB - /// If true, this order does not accept buying more /// than `amountB`. /// @param walletId The id of the wallet that generated this order. /// @param marginSplitPercentage - /// The percentage of margin paid to miner. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. struct Order { address owner; address tokenS; address tokenB; address authAddr; uint validSince; uint validUntil; uint amountS; uint amountB; uint lrcFee; bool buyNoMoreThanAmountB; uint walletId; uint8 marginSplitPercentage; } /// @param order The original order /// @param orderHash The order&#39;s hash /// @param feeSelection - /// A miner-supplied value indicating if LRC (value = 0) /// or margin split is choosen by the miner (value = 1). /// We may support more fee model in the future. /// @param rate Exchange rate provided by miner. /// @param fillAmountS Amount of tokenS to sell, calculated by protocol. /// @param lrcReward The amount of LRC paid by miner to order owner in /// exchange for margin split. /// @param lrcFee The amount of LR paid by order owner to miner. /// @param splitS TokenS paid to miner. /// @param splitB TokenB paid to miner. struct OrderState { Order order; bytes32 orderHash; bool marginSplitAsFee; Rate rate; uint fillAmountS; uint lrcReward; uint lrcFee; uint splitS; uint splitB; } /// @dev A struct to capture parameters passed to submitRing method and /// various of other variables used across the submitRing core logics. struct RingParams { address[3][] addressList; uint[7][] uintArgsList; uint8[1][] uint8ArgsList; bool[] buyNoMoreThanAmountBList; uint8[] vList; bytes32[] rList; bytes32[] sList; uint minerId; uint ringSize; // computed uint16 feeSelections; address ringMiner; // queried address feeRecipient; // queried bytes32 ringHash; // computed } //////////////////////////////////////////////////////////////////////////// /// Constructor /// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Disable default function. function () payable public { revert(); } function cancelOrder( address[4] addresses, uint[7] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) external { uint cancelAmount = orderValues[6]; require(cancelAmount > 0); // "amount to cancel is zero"); Order memory order = Order( addresses[0], addresses[1], addresses[2], addresses[3], orderValues[2], orderValues[3], orderValues[0], orderValues[1], orderValues[4], buyNoMoreThanAmountB, orderValues[5], marginSplitPercentage ); require(msg.sender == order.owner); // "cancelOrder not submitted by order owner"); bytes32 orderHash = calculateOrderHash(order); verifySignature( order.owner, orderHash, v, r, s ); cancelled[orderHash] = cancelled[orderHash].add(cancelAmount); cancelledOrFilled[orderHash] = cancelledOrFilled[orderHash].add(cancelAmount); emit OrderCancelled(orderHash, cancelAmount); } function cancelAllOrdersByTradingPair( address token1, address token2, uint cutoff ) external { uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff; bytes20 tokenPair = bytes20(token1) ^ bytes20(token2); require(tradingPairCutoffs[msg.sender][tokenPair] < t); // "attempted to set cutoff to a smaller value" tradingPairCutoffs[msg.sender][tokenPair] = t; emit OrdersCancelled( msg.sender, token1, token2, t ); } function cancelAllOrders(uint cutoff) external { uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff; require(cutoffs[msg.sender] < t); // "attempted to set cutoff to a smaller value" cutoffs[msg.sender] = t; emit AllOrdersCancelled(msg.sender, t); } function submitRing( address[3][] addressList, uint[7][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, uint minerId, uint16 feeSelections ) public { // Check if the highest bit of ringIndex is &#39;1&#39;. require(ringIndex & ENTERED_MASK != ENTERED_MASK); // "attempted to re-ent submitRing function"); // Set the highest bit of ringIndex to &#39;1&#39;. ringIndex |= ENTERED_MASK; RingParams memory params = RingParams( addressList, uintArgsList, uint8ArgsList, buyNoMoreThanAmountBList, vList, rList, sList, minerId, addressList.length, feeSelections, 0x0, // ringMiner 0x0, // feeRecipient 0x0 // ringHash ); verifyInputDataIntegrity(params); updateFeeRecipient(params); // Assemble input data into structs so we can pass them to other functions. // This method also calculates ringHash, therefore it must be called before // calling `verifyRingSignatures`. OrderState[] memory orders = assembleOrders(params); verifyRingSignatures(params); verifyTokensRegistered(params); handleRing(params, orders); ringIndex = (ringIndex ^ ENTERED_MASK) + 1; } //////////////////////////////////////////////////////////////////////////// /// Internal & Private Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Validate a ring. function verifyRingHasNoSubRing( uint ringSize, OrderState[] orders ) private pure { // Check the ring has no sub-ring. for (uint i = 0; i < ringSize - 1; i++) { address tokenS = orders[i].order.tokenS; for (uint j = i + 1; j < ringSize; j++) { require(tokenS != orders[j].order.tokenS); // "found sub-ring"); } } } /// @dev Verify the ringHash has been signed with each order&#39;s auth private /// keys as well as the miner&#39;s private key. function verifyRingSignatures(RingParams params) private pure { uint j; for (uint i = 0; i < params.ringSize; i++) { j = i + params.ringSize; verifySignature( params.addressList[i][2], // authAddr params.ringHash, params.vList[j], params.rList[j], params.sList[j] ); } if (params.ringMiner != 0x0) { j++; verifySignature( params.ringMiner, params.ringHash, params.vList[j], params.rList[j], params.sList[j] ); } } function verifyTokensRegistered(RingParams params) private view { // Extract the token addresses address[] memory tokens = new address[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { tokens[i] = params.addressList[i][1]; } // Test all token addresses at once require( TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens) ); // "token not registered"); } function updateFeeRecipient(RingParams params) private view { if (params.minerId == 0) { params.feeRecipient = msg.sender; } else { (params.feeRecipient, params.ringMiner) = NameRegistry( nameRegistryAddress ).getParticipantById( params.minerId ); if (params.feeRecipient == 0x0) { params.feeRecipient = msg.sender; } } uint sigSize = params.ringSize * 2; if (params.ringMiner != 0x0) { sigSize += 1; } require(sigSize == params.vList.length); // "ring data is inconsistent - vList"); require(sigSize == params.rList.length); // "ring data is inconsistent - rList"); require(sigSize == params.sList.length); // "ring data is inconsistent - sList"); } function handleRing( RingParams params, OrderState[] orders ) private { uint64 _ringIndex = ringIndex ^ ENTERED_MASK; address _lrcTokenAddress = lrcTokenAddress; TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); // Do the hard work. verifyRingHasNoSubRing(params.ringSize, orders); // Exchange rates calculation are performed by ring-miners as solidity // cannot get power-of-1/n operation, therefore we have to verify // these rates are correct. verifyMinerSuppliedFillRates(params.ringSize, orders); // Scale down each order independently by substracting amount-filled and // amount-cancelled. Order owner&#39;s current balance and allowance are // not taken into consideration in these operations. scaleRingBasedOnHistoricalRecords(delegate, params.ringSize, orders); // Based on the already verified exchange rate provided by ring-miners, // we can furthur scale down orders based on token balance and allowance, // then find the smallest order of the ring, then calculate each order&#39;s // `fillAmountS`. calculateRingFillAmount(params.ringSize, orders); // Calculate each order&#39;s `lrcFee` and `lrcRewrard` and splict how much // of `fillAmountS` shall be paid to matching order or miner as margin // split. calculateRingFees( delegate, params.ringSize, orders, params.feeRecipient, _lrcTokenAddress ); /// Make transfers. bytes32[] memory orderHashList; uint[6][] memory amountsList; (orderHashList, amountsList) = settleRing( delegate, params.ringSize, orders, params.feeRecipient, _lrcTokenAddress ); emit RingMined( _ringIndex, params.ringHash, params.ringMiner, params.feeRecipient, orderHashList, amountsList ); } function settleRing( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address feeRecipient, address _lrcTokenAddress ) private returns ( bytes32[] memory orderHashList, uint[6][] memory amountsList) { bytes32[] memory batch = new bytes32[](ringSize * 7); // ringSize * (owner + tokenS + 4 amounts + walletAddrress) orderHashList = new bytes32[](ringSize); amountsList = new uint[6][](ringSize); uint p = 0; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; Order memory order = state.order; uint prevSplitB = orders[(i + ringSize - 1) % ringSize].splitB; uint nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; // Store owner and tokenS of every order batch[p] = bytes32(order.owner); batch[p + 1] = bytes32(order.tokenS); // Store all amounts batch[p + 2] = bytes32(state.fillAmountS - prevSplitB); batch[p + 3] = bytes32(prevSplitB + state.splitS); batch[p + 4] = bytes32(state.lrcReward); batch[p + 5] = bytes32(state.lrcFee); if (order.walletId != 0) { batch[p + 6] = bytes32(NameRegistry(nameRegistryAddress).getFeeRecipientById(order.walletId)); } else { batch[p + 6] = bytes32(0x0); } p += 7; // Update fill records if (order.buyNoMoreThanAmountB) { cancelledOrFilled[state.orderHash] += nextFillAmountS; } else { cancelledOrFilled[state.orderHash] += state.fillAmountS; } orderHashList[i] = state.orderHash; amountsList[i][0] = state.fillAmountS + state.splitS; amountsList[i][1] = nextFillAmountS - state.splitB; amountsList[i][2] = state.lrcReward; amountsList[i][3] = state.lrcFee; amountsList[i][4] = state.splitS; amountsList[i][5] = state.splitB; } // Do all transactions delegate.batchTransferToken( _lrcTokenAddress, feeRecipient, walletSplitPercentage, batch ); } /// @dev Verify miner has calculte the rates correctly. function verifyMinerSuppliedFillRates( uint ringSize, OrderState[] orders ) private view { uint[] memory rateRatios = new uint[](ringSize); uint _rateRatioScale = RATE_RATIO_SCALE; for (uint i = 0; i < ringSize; i++) { uint s1b0 = orders[i].rate.amountS.mul(orders[i].order.amountB); uint s0b1 = orders[i].order.amountS.mul(orders[i].rate.amountB); require(s1b0 <= s0b1); // "miner supplied exchange rate provides invalid discount"); rateRatios[i] = _rateRatioScale.mul(s1b0) / s0b1; } uint cvs = MathUint.cvsquare(rateRatios, _rateRatioScale); require(cvs <= rateRatioCVSThreshold); // "miner supplied exchange rate is not evenly discounted"); } /// @dev Calculate each order&#39;s fee or LRC reward. function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address feeRecipient, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFee == 0) { // When an order&#39;s LRC fee is 0 or smaller than the specified fee, // we help miner automatically select margin-split. state.marginSplitAsFee = true; state.order.marginSplitPercentage = _marginSplitPercentageBase; } else { uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.order.owner ); // If the order is selling LRC, we need to calculate how much LRC // is left that can be used as fee. if (state.order.tokenS == _lrcTokenAddress) { lrcSpendable -= state.fillAmountS; } // If the order is buyign LRC, it will has more to pay as fee. if (state.order.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable + lrcReceiable; // If order doesn&#39;t have enough LRC, set margin split to 100%. if (lrcTotal < state.lrcFee) { state.lrcFee = lrcTotal; state.order.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFee == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFee) { state.splitB = state.lrcFee; state.lrcFee = 0; } else { state.splitB = lrcReceiable; state.lrcFee -= lrcReceiable; } } } else { // Only check the available miner balance when absolutely needed if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFee) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, feeRecipient); } // Only calculate split when miner has enough LRC; // otherwise all splits are 0. if (minerLrcSpendable >= state.lrcFee) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.order.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.order.amountS ) / state.order.amountB).sub( state.fillAmountS ); } else { split = nextFillAmountS.sub( state.fillAmountS.mul( state.order.amountB ) / state.order.amountS ); } if (state.order.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.order.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.order.buyNoMoreThanAmountB) { state.splitS = split; } else { state.splitB = split; } // This implicits order with smaller index in the ring will // be paid LRC reward first, so the orders in the ring does // mater. if (split > 0) { minerLrcSpendable -= state.lrcFee; state.lrcReward = state.lrcFee; } } state.lrcFee = 0; } } } /// @dev Calculate each order&#39;s fill amount. function calculateRingFillAmount( uint ringSize, OrderState[] orders ) private pure { uint smallestIdx = 0; uint i; uint j; for (i = 0; i < ringSize; i++) { j = (i + 1) % ringSize; smallestIdx = calculateOrderFillAmount( orders[i], orders[j], i, j, smallestIdx ); } for (i = 0; i < smallestIdx; i++) { calculateOrderFillAmount( orders[i], orders[(i + 1) % ringSize], 0, // Not needed 0, // Not needed 0 // Not needed ); } } /// @return The smallest order&#39;s index. function calculateOrderFillAmount( OrderState state, OrderState next, uint i, uint j, uint smallestIdx ) private pure returns (uint newSmallestIdx) { // Default to the same smallest index newSmallestIdx = smallestIdx; uint fillAmountB = state.fillAmountS.mul( state.rate.amountB ) / state.rate.amountS; if (state.order.buyNoMoreThanAmountB) { if (fillAmountB > state.order.amountB) { fillAmountB = state.order.amountB; state.fillAmountS = fillAmountB.mul( state.rate.amountS ) / state.rate.amountB; newSmallestIdx = i; } state.lrcFee = state.order.lrcFee.mul( fillAmountB ) / state.order.amountB; } else { state.lrcFee = state.order.lrcFee.mul( state.fillAmountS ) / state.order.amountS; } if (fillAmountB <= next.fillAmountS) { next.fillAmountS = fillAmountB; } else { newSmallestIdx = j; } } /// @dev Scale down all orders based on historical fill or cancellation /// stats but key the order&#39;s original exchange rate. function scaleRingBasedOnHistoricalRecords( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders ) private view { for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; Order memory order = state.order; uint amount; if (order.buyNoMoreThanAmountB) { amount = order.amountB.tolerantSub( cancelledOrFilled[state.orderHash] ); order.amountS = amount.mul(order.amountS) / order.amountB; order.lrcFee = amount.mul(order.lrcFee) / order.amountB; order.amountB = amount; } else { amount = order.amountS.tolerantSub( cancelledOrFilled[state.orderHash] ); order.amountB = amount.mul(order.amountB) / order.amountS; order.lrcFee = amount.mul(order.lrcFee) / order.amountS; order.amountS = amount; } require(order.amountS > 0); // "amountS is zero"); require(order.amountB > 0); // "amountB is zero"); uint availableAmountS = getSpendable(delegate, order.tokenS, order.owner); require(availableAmountS > 0); // "order spendable amountS is zero"); state.fillAmountS = ( order.amountS < availableAmountS ? order.amountS : availableAmountS ); } } /// @return Amount of ERC20 token that can be spent by this contract. function getSpendable( TokenTransferDelegate delegate, address tokenAddress, address tokenOwner ) private view returns (uint) { ERC20 token = ERC20(tokenAddress); uint allowance = token.allowance( tokenOwner, address(delegate) ); uint balance = token.balanceOf(tokenOwner); return (allowance < balance ? allowance : balance); } /// @dev verify input data&#39;s basic integrity. function verifyInputDataIntegrity(RingParams params) private pure { require(params.ringSize == params.addressList.length); // "ring data is inconsistent - addressList"); require(params.ringSize == params.uintArgsList.length); // "ring data is inconsistent - uintArgsList"); require(params.ringSize == params.uint8ArgsList.length); // "ring data is inconsistent - uint8ArgsList"); require(params.ringSize == params.buyNoMoreThanAmountBList.length); // "ring data is inconsistent - buyNoMoreThanAmountBList"); // Validate ring-mining related arguments. for (uint i = 0; i < params.ringSize; i++) { require(params.uintArgsList[i][5] > 0); // "order rateAmountS is zero"); } //Check ring size require(params.ringSize > 1 && params.ringSize <= MAX_RING_SIZE); // "invalid ring size"); } /// @dev assmble order parameters into Order struct. /// @return A list of orders. function assembleOrders(RingParams params) private view returns (OrderState[] memory orders) { orders = new OrderState[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { Order memory order = Order( params.addressList[i][0], params.addressList[i][1], params.addressList[(i + 1) % params.ringSize][1], params.addressList[i][2], params.uintArgsList[i][2], params.uintArgsList[i][3], params.uintArgsList[i][0], params.uintArgsList[i][1], params.uintArgsList[i][4], params.buyNoMoreThanAmountBList[i], params.uintArgsList[i][6], params.uint8ArgsList[i][0] ); validateOrder(order); bytes32 orderHash = calculateOrderHash(order); verifySignature( order.owner, orderHash, params.vList[i], params.rList[i], params.sList[i] ); bool marginSplitAsFee = (params.feeSelections & (uint16(1) << i)) > 0; orders[i] = OrderState( order, orderHash, marginSplitAsFee, Rate(params.uintArgsList[i][5], order.amountB), 0, // fillAmountS 0, // lrcReward 0, // lrcFee 0, // splitS 0 // splitB ); params.ringHash ^= orderHash; } params.ringHash = keccak256( params.ringHash, params.minerId, params.feeSelections ); } /// @dev validate order&#39;s parameters are OK. function validateOrder(Order order) private view { require(order.owner != 0x0); // invalid order owner require(order.tokenS != 0x0); // invalid order tokenS require(order.tokenB != 0x0); // invalid order tokenB require(order.amountS != 0); // invalid order amountS require(order.amountB != 0); // invalid order amountB require(order.marginSplitPercentage <= MARGIN_SPLIT_PERCENTAGE_BASE); // invalid order marginSplitPercentage require(order.validSince <= block.timestamp); // order is too early to match require(order.validUntil > block.timestamp); // order is expired bytes20 tradingPair = bytes20(order.tokenS) ^ bytes20(order.tokenB); require(order.validSince > tradingPairCutoffs[order.owner][tradingPair]); // order trading pair is cut off require(order.validSince > cutoffs[order.owner]); // order is cut off } /// @dev Get the Keccak-256 hash of order with specified parameters. function calculateOrderHash(Order order) private view returns (bytes32) { return keccak256( address(this), order.owner, order.tokenS, order.tokenB, order.authAddr, order.amountS, order.amountB, order.validSince, order.validUntil, order.lrcFee, order.buyNoMoreThanAmountB, order.walletId, order.marginSplitPercentage ); } /// @dev Verify signer&#39;s signature. function verifySignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s ) private pure { require( signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ) ); // "invalid signature"); } function getTradingPairCutoffs(address orderOwner, address token1, address token2) public view returns (uint) { bytes20 tokenPair = bytes20(token1) ^ bytes20(token2); return tradingPairCutoffs[orderOwner][tokenPair]; } }
Do the hard work. Exchange rates calculation are performed by ring-miners as solidity cannot get power-of-1/n operation, therefore we have to verify these rates are correct. Scale down each order independently by substracting amount-filled and amount-cancelled. Order owner&#39;s current balance and allowance are not taken into consideration in these operations. Based on the already verified exchange rate provided by ring-miners, we can furthur scale down orders based on token balance and allowance, then find the smallest order of the ring, then calculate each order&#39;s `fillAmountS`. Calculate each order&#39;s `lrcFee` and `lrcRewrard` and splict how much of `fillAmountS` shall be paid to matching order or miner as margin split.
function handleRing( RingParams params, OrderState[] orders ) private { uint64 _ringIndex = ringIndex ^ ENTERED_MASK; address _lrcTokenAddress = lrcTokenAddress; TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); verifyRingHasNoSubRing(params.ringSize, orders); verifyMinerSuppliedFillRates(params.ringSize, orders); scaleRingBasedOnHistoricalRecords(delegate, params.ringSize, orders); calculateRingFillAmount(params.ringSize, orders); calculateRingFees( delegate, params.ringSize, orders, params.feeRecipient, _lrcTokenAddress ); bytes32[] memory orderHashList; uint[6][] memory amountsList; (orderHashList, amountsList) = settleRing( delegate, params.ringSize, orders, params.feeRecipient, _lrcTokenAddress ); emit RingMined( _ringIndex, params.ringHash, params.ringMiner, params.feeRecipient, orderHashList, amountsList );
10,672,403
[ 1, 3244, 326, 7877, 1440, 18, 18903, 17544, 11096, 854, 9591, 635, 9221, 17, 1154, 414, 487, 18035, 560, 2780, 336, 7212, 17, 792, 17, 21, 19, 82, 1674, 16, 13526, 732, 1240, 358, 3929, 4259, 17544, 854, 3434, 18, 12591, 2588, 1517, 1353, 14807, 715, 635, 2373, 621, 310, 3844, 17, 13968, 471, 3844, 17, 10996, 1259, 18, 4347, 3410, 10, 5520, 31, 87, 783, 11013, 471, 1699, 1359, 854, 486, 9830, 1368, 5260, 367, 316, 4259, 5295, 18, 25935, 603, 326, 1818, 13808, 7829, 4993, 2112, 635, 9221, 17, 1154, 414, 16, 732, 848, 284, 295, 451, 295, 3159, 2588, 11077, 2511, 603, 1147, 11013, 471, 1699, 1359, 16, 1508, 1104, 326, 13541, 1353, 434, 326, 9221, 16, 1508, 4604, 1517, 1353, 10, 5520, 31, 87, 1375, 5935, 6275, 55, 8338, 9029, 1517, 1353, 10, 5520, 31, 87, 1375, 80, 1310, 14667, 68, 471, 1375, 80, 1310, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 1640, 10369, 12, 203, 3639, 25463, 1370, 565, 859, 16, 203, 3639, 4347, 1119, 8526, 225, 11077, 203, 3639, 262, 203, 3639, 3238, 203, 565, 288, 203, 3639, 2254, 1105, 389, 8022, 1016, 273, 9221, 1016, 3602, 20018, 2056, 67, 11704, 31, 203, 3639, 1758, 389, 80, 1310, 1345, 1887, 273, 328, 1310, 1345, 1887, 31, 203, 3639, 3155, 5912, 9586, 7152, 273, 3155, 5912, 9586, 12, 22216, 1887, 1769, 203, 3639, 3929, 10369, 5582, 2279, 1676, 10369, 12, 2010, 18, 8022, 1225, 16, 11077, 1769, 203, 3639, 3929, 2930, 264, 3088, 3110, 8026, 20836, 12, 2010, 18, 8022, 1225, 16, 11077, 1769, 203, 3639, 3159, 10369, 9802, 1398, 8648, 10129, 6499, 12, 22216, 16, 859, 18, 8022, 1225, 16, 11077, 1769, 203, 3639, 4604, 10369, 8026, 6275, 12, 2010, 18, 8022, 1225, 16, 11077, 1769, 203, 3639, 4604, 10369, 2954, 281, 12, 203, 5411, 7152, 16, 203, 5411, 859, 18, 8022, 1225, 16, 203, 5411, 11077, 16, 203, 5411, 859, 18, 21386, 18241, 16, 203, 5411, 389, 80, 1310, 1345, 1887, 203, 3639, 11272, 203, 3639, 1731, 1578, 8526, 3778, 1353, 2310, 682, 31, 203, 3639, 2254, 63, 26, 6362, 65, 3778, 3844, 21576, 31, 203, 3639, 261, 1019, 2310, 682, 16, 3844, 21576, 13, 273, 444, 5929, 10369, 12, 203, 5411, 7152, 16, 203, 5411, 859, 18, 8022, 1225, 16, 203, 5411, 11077, 16, 203, 5411, 859, 18, 21386, 18241, 16, 203, 5411, 389, 80, 1310, 1345, 1887, 203, 3639, 11272, 203, 3639, 3626, 25463, 49, 1920, 12, 203, 5411, 2 ]
pragma solidity^0.4.24; // Contract to generate random number // Uses timestamp and difficulty // Not recommended contract RNG { function generateRandom() view returns (uint) { return uint256(keccak256( abi.encodePacked(block.timestamp, block.difficulty) )); } } pragma solidity^0.4.24; contract Lottery { // Structure of a bid struct Bid { uint num; uint blockNum; } // Mapping to store bods mapping(address => Bid) bids; // Function to select the winner based on future block hash function isWon() public view returns (bool) { uint bid = bids[msg.sender].num; uint blockNum = bids[msg.sender].blockNum; require(blockNum >= block.number); uint winner = uint(keccak256( abi.encodePacked(blockhash(blockNum + 3)) )); return (bid == winner); } }
Contract to generate random number Uses timestamp and difficulty Not recommended
contract RNG { function generateRandom() view returns (uint) { return uint256(keccak256( abi.encodePacked(block.timestamp, block.difficulty) )); } }
7,245,854
[ 1, 8924, 358, 2103, 2744, 1300, 14854, 2858, 471, 3122, 21934, 2288, 14553, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 534, 4960, 288, 203, 565, 445, 2103, 8529, 1435, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 2629, 18, 5508, 16, 1203, 18, 5413, 21934, 13, 203, 3639, 262, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/44787/0xa9288B382Cf210Cc879590A0199ceFD91633eE12/sources/contracts/Fundraise.sol
add donation to campaign add contributor to donation list update number of contributors
function fundCampaign(uint campaignId) public payable onlyWhenNotPaused { require(msg.value >= minFund, "Not enough to fund"); require(!isEnded(campaignId), "Fundraising finished"); uint _donationId = campaigns[campaignId].contributors; campaigns[campaignId].raisedFunds += msg.value; campaigns[campaignId] .donations .donationId = _donationId; campaigns[campaignId] .donations .contributor = msg.sender; campaigns[campaignId] .donations .amount = msg.value; campaigns[campaignId].contributors++; emit CampaignFunded(campaignId, _donationId, msg.sender, msg.value); }
13,256,432
[ 1, 1289, 2727, 367, 358, 8965, 527, 31123, 358, 2727, 367, 666, 1089, 1300, 434, 13608, 13595, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 284, 1074, 13432, 12, 11890, 8965, 548, 13, 1071, 8843, 429, 1338, 9434, 1248, 28590, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 1131, 42, 1074, 16, 315, 1248, 7304, 358, 284, 1074, 8863, 203, 3639, 2583, 12, 5, 291, 28362, 12, 14608, 548, 3631, 315, 42, 1074, 354, 13734, 6708, 8863, 203, 203, 3639, 2254, 389, 19752, 367, 548, 273, 8965, 87, 63, 14608, 548, 8009, 26930, 13595, 31, 203, 540, 203, 3639, 8965, 87, 63, 14608, 548, 8009, 354, 5918, 42, 19156, 1011, 1234, 18, 1132, 31, 203, 540, 203, 203, 3639, 8965, 87, 63, 14608, 548, 65, 203, 5411, 263, 19752, 1012, 203, 5411, 263, 19752, 367, 548, 273, 389, 19752, 367, 548, 31, 203, 203, 3639, 8965, 87, 63, 14608, 548, 65, 203, 5411, 263, 19752, 1012, 203, 5411, 263, 591, 19293, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 8965, 87, 63, 14608, 548, 65, 203, 5411, 263, 19752, 1012, 203, 5411, 263, 8949, 273, 1234, 18, 1132, 31, 203, 203, 3639, 8965, 87, 63, 14608, 548, 8009, 26930, 13595, 9904, 31, 203, 203, 3639, 3626, 17820, 42, 12254, 12, 14608, 548, 16, 389, 19752, 367, 548, 16, 1234, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.11; // DssExec.sol -- MakerDAO Executive Spell Template // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. interface PauseAbstract { function delay() external view returns (uint256); function plot(address, bytes32, bytes calldata, uint256) external; function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory); } interface Changelog { function getAddress(bytes32) external view returns (address); } interface SpellAction { function officeHours() external view returns (bool); } contract DssExec { Changelog constant public log = Changelog(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F); uint256 public eta; bytes public sig; bool public done; bytes32 immutable public tag; address immutable public action; uint256 immutable public expiration; PauseAbstract immutable public pause; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" string public description; function officeHours() external view returns (bool) { return SpellAction(action).officeHours(); } function nextCastTime() external view returns (uint256 castTime) { require(eta != 0, "DssExec/spell-not-scheduled"); castTime = block.timestamp > eta ? block.timestamp : eta; // Any day at XX:YY if (SpellAction(action).officeHours()) { uint256 day = (castTime / 1 days + 3) % 7; uint256 hour = castTime / 1 hours % 24; uint256 minute = castTime / 1 minutes % 60; uint256 second = castTime % 60; if (day >= 5) { castTime += (6 - day) * 1 days; // Go to Sunday XX:YY castTime += (24 - hour + 14) * 1 hours; // Go to 14:YY UTC Monday castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } else { if (hour >= 21) { if (day == 4) castTime += 2 days; // If Friday, fast forward to Sunday XX:YY castTime += (24 - hour + 14) * 1 hours; // Go to 14:YY UTC next day castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } else if (hour < 14) { castTime += (14 - hour) * 1 hours; // Go to 14:YY UTC same day castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } } } } // @param _description A string description of the spell // @param _expiration The timestamp this spell will expire. (Ex. now + 30 days) // @param _spellAction The address of the spell action constructor(string memory _description, uint256 _expiration, address _spellAction) public { pause = PauseAbstract(log.getAddress("MCD_PAUSE")); description = _description; expiration = _expiration; action = _spellAction; sig = abi.encodeWithSignature("execute()"); bytes32 _tag; // Required for assembly access address _action = _spellAction; // Required for assembly access assembly { _tag := extcodehash(_action) } tag = _tag; } function schedule() public { require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + PauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); } function cast() public { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } } // DssAction.sol -- DSS Executive Spell Actions // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // DssExecLib.sol -- MakerDAO Executive Spellcrafting Library // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. library DssExecLib { function vat() public view returns (address) {} function jug() public view returns (address) {} function spotter() public view returns (address) {} function getChangelogAddress(bytes32) public view returns (address) {} function setChangelogAddress(bytes32, address) public {} function setChangelogVersion(string memory) public {} function authorize(address, address) public {} function updateCollateralPrice(bytes32) public {} function setContract(address, bytes32, bytes32, address) public {} function increaseGlobalDebtCeiling(uint256) public {} function setMaxTotalDAILiquidationAmount(uint256) public {} function setIlkDebtCeiling(bytes32, uint256) public {} function setIlkAutoLineParameters(bytes32, uint256, uint256, uint256) public {} function setIlkMinVaultAmount(bytes32, uint256) public {} function setIlkLiquidationRatio(bytes32, uint256) public {} function setIlkMinAuctionBidIncrease(bytes32, uint256) public {} function setIlkBidDuration(bytes32, uint256) public {} function setIlkAuctionDuration(bytes32, uint256) public {} function setIlkStabilityFee(bytes32, uint256, bool) public {} } interface OracleLike { function src() external view returns (address); } abstract contract DssAction { using DssExecLib for *; // Office Hours defaults to true by default. // To disable office hours, override this function and // return false in the inherited action. function officeHours() public virtual returns (bool) { return true; } // DssExec calls execute. We limit this function subject to officeHours modifier. function execute() external limited { actions(); } // DssAction developer must override `actions()` and place all actions to be called inside. // The DssExec function will call this subject to the officeHours limiter // By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time. function actions() public virtual; // Modifier required to modifier limited { if (officeHours()) { uint day = (block.timestamp / 1 days + 3) % 7; require(day < 5, "Can only be cast on a weekday"); uint hour = block.timestamp / 1 hours % 24; require(hour >= 14 && hour < 21, "Outside office hours"); } _; } } interface GemJoinAbstract { function vat() external view returns (address); function ilk() external view returns (bytes32); function gem() external view returns (address); function dec() external view returns (uint256); } interface DSTokenAbstract { function decimals() external view returns (uint256); } interface Initializable { function init(bytes32) external; } interface Hopeable { function hope(address) external; } interface Kissable { function kiss(address) external; } interface RwaLiquidationLike { function ilks(bytes32) external returns (bytes32,address,uint48,uint48); function init(bytes32, uint256, string calldata, uint48) external; } contract DssSpellAction is DssAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/5925c52da6f8d485447228ca5acd435997522de6/governance/votes/Executive%20vote%20-%20March%205%2C%202021.md -q -O - 2>/dev/null)" string public constant description = "2021-03-05 MakerDAO Executive Spell | Hash: 0xb9829a5159cc2270de0592c8fcb9f7cbcc79491e26ad7ded78afb7994227f18b"; // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' // // A table of rates can be found at // https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW // uint256 constant THREE_PCT_RATE = 1000000000937303470807876289; uint256 constant MILLION = 10**6; uint256 constant WAD = 10**18; uint256 constant RAD = 10**45; address constant RWA001_OPERATOR = 0x7709f0840097170E5cB1F8c890AcB8601d73b35f; address constant RWA001_GEM = 0x10b2aA5D77Aa6484886d8e244f0686aB319a270d; address constant MCD_JOIN_RWA001_A = 0x476b81c12Dc71EDfad1F64B9E07CaA60F4b156E2; address constant RWA001_A_URN = 0xa3342059BcDcFA57a13b12a35eD4BBE59B873005; address constant RWA001_A_INPUT_CONDUIT = 0x486C85e2bb9801d14f6A8fdb78F5108a0fd932f2; address constant RWA001_A_OUTPUT_CONDUIT = 0xb3eFb912e1cbC0B26FC17388Dd433Cecd2206C3d; address constant MIP21_LIQUIDATION_ORACLE = 0x88f88Bb9E66241B73B84f3A6E197FbBa487b1E30; address constant SC_DOMAIN_DEPLOYER_07 = 0xDA0FaB0700A4389F6E6679aBAb1692B4601ce9bf; function actions() public override { // Increase ETH-A target available debt (gap) from 30M to 80M DssExecLib.setIlkAutoLineParameters("ETH-A", 2_500 * MILLION, 80 * MILLION, 12 hours); // Decrease the bid duration (ttl) and max auction duration (tau) from 6 to 4 hours to all the ilks with liquidation on DssExecLib.setIlkBidDuration("ETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("ETH-A", 4 hours); DssExecLib.setIlkBidDuration("ETH-B", 4 hours); DssExecLib.setIlkAuctionDuration("ETH-B", 4 hours); DssExecLib.setIlkBidDuration("BAT-A", 4 hours); DssExecLib.setIlkAuctionDuration("BAT-A", 4 hours); DssExecLib.setIlkBidDuration("WBTC-A", 4 hours); DssExecLib.setIlkAuctionDuration("WBTC-A", 4 hours); DssExecLib.setIlkBidDuration("KNC-A", 4 hours); DssExecLib.setIlkAuctionDuration("KNC-A", 4 hours); DssExecLib.setIlkBidDuration("ZRX-A", 4 hours); DssExecLib.setIlkAuctionDuration("ZRX-A", 4 hours); DssExecLib.setIlkBidDuration("MANA-A", 4 hours); DssExecLib.setIlkAuctionDuration("MANA-A", 4 hours); DssExecLib.setIlkBidDuration("USDT-A", 4 hours); DssExecLib.setIlkAuctionDuration("USDT-A", 4 hours); DssExecLib.setIlkBidDuration("COMP-A", 4 hours); DssExecLib.setIlkAuctionDuration("COMP-A", 4 hours); DssExecLib.setIlkBidDuration("LRC-A", 4 hours); DssExecLib.setIlkAuctionDuration("LRC-A", 4 hours); DssExecLib.setIlkBidDuration("LINK-A", 4 hours); DssExecLib.setIlkAuctionDuration("LINK-A", 4 hours); DssExecLib.setIlkBidDuration("BAL-A", 4 hours); DssExecLib.setIlkAuctionDuration("BAL-A", 4 hours); DssExecLib.setIlkBidDuration("YFI-A", 4 hours); DssExecLib.setIlkAuctionDuration("YFI-A", 4 hours); DssExecLib.setIlkBidDuration("UNI-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNI-A", 4 hours); DssExecLib.setIlkBidDuration("RENBTC-A", 4 hours); DssExecLib.setIlkAuctionDuration("RENBTC-A", 4 hours); DssExecLib.setIlkBidDuration("AAVE-A", 4 hours); DssExecLib.setIlkAuctionDuration("AAVE-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2DAIETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2DAIETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2WBTCETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2WBTCETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2USDCETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2USDCETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2ETHUSDT-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2ETHUSDT-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2LINKETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2LINKETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2UNIETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2UNIETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2WBTCDAI-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2WBTCDAI-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2AAVEETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2AAVEETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2DAIUSDT-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2DAIUSDT-A", 4 hours); // Increase the box parameter from 15M to 20M DssExecLib.setMaxTotalDAILiquidationAmount(20 * MILLION); // Increase the minimum bid increment (beg) from 3% to 5% for the following collaterals DssExecLib.setIlkMinAuctionBidIncrease("ETH-B", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2USDCETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2WBTCETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2DAIETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2UNIETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2ETHUSDT-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2LINKETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2WBTCDAI-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2AAVEETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2DAIUSDT-A", 500); // RWA001-A collateral deploy bytes32 ilk = "RWA001-A"; address vat = DssExecLib.vat(); // Sanity checks require(GemJoinAbstract(MCD_JOIN_RWA001_A).vat() == vat, "join-vat-not-match"); require(GemJoinAbstract(MCD_JOIN_RWA001_A).ilk() == ilk, "join-ilk-not-match"); require(GemJoinAbstract(MCD_JOIN_RWA001_A).gem() == RWA001_GEM, "join-gem-not-match"); require(GemJoinAbstract(MCD_JOIN_RWA001_A).dec() == DSTokenAbstract(RWA001_GEM).decimals(), "join-dec-not-match"); // init the RwaLiquidationOracle // Oracle initial price: 1060 // doc: "https://ipfs.io/ipfs/QmdmAUTU3sd9VkdfTZNQM6krc9jsKgF2pz7W1qvvfJo1xk" // MIP13c3-SP4 Declaration of Intent & Commercial Points - // Off-Chain Asset Backed Lender to onboard Real World Assets // as Collateral for a DAI loan // tau: 30 days RwaLiquidationLike(MIP21_LIQUIDATION_ORACLE).init( ilk, 1060 * WAD, "QmdmAUTU3sd9VkdfTZNQM6krc9jsKgF2pz7W1qvvfJo1xk", 30 days ); (,address pip,,) = RwaLiquidationLike(MIP21_LIQUIDATION_ORACLE).ilks(ilk); // Set price feed for RWA001 DssExecLib.setContract(DssExecLib.spotter(), ilk, "pip", pip); // Init RWA-001 in Vat Initializable(vat).init(ilk); // Init RWA-001 in Jug Initializable(DssExecLib.jug()).init(ilk); // Allow RWA-001 Join to modify Vat registry DssExecLib.authorize(vat, MCD_JOIN_RWA001_A); // Allow RwaLiquidationOracle to modify Vat registry DssExecLib.authorize(vat, MIP21_LIQUIDATION_ORACLE); // Increase the global debt ceiling by the ilk ceiling DssExecLib.increaseGlobalDebtCeiling(1_000); // Set the ilk debt ceiling DssExecLib.setIlkDebtCeiling(ilk, 1_000); // No dust // DssExecLib.setIlkMinVaultAmount(ilk, 0); // 3% stability fee DssExecLib.setIlkStabilityFee(ilk, THREE_PCT_RATE, false); // collateralization ratio 100% DssExecLib.setIlkLiquidationRatio(ilk, 10_000); // poke the spotter to pull in a price DssExecLib.updateCollateralPrice(ilk); // give the urn permissions on the join adapter DssExecLib.authorize(MCD_JOIN_RWA001_A, RWA001_A_URN); // set up the urn Hopeable(RWA001_A_URN).hope(RWA001_OPERATOR); // set up output conduit Hopeable(RWA001_A_OUTPUT_CONDUIT).hope(RWA001_OPERATOR); // Authorize the SC Domain team deployer address on the output conduit during introductory phase. // This allows the SC team to assist in the testing of a complete circuit. // Once a broker dealer arrangement is established the deployer address should be `deny`ed on the conduit. Kissable(RWA001_A_OUTPUT_CONDUIT).kiss(SC_DOMAIN_DEPLOYER_07); // add RWA-001 contract to the changelog DssExecLib.setChangelogAddress("RWA001", RWA001_GEM); DssExecLib.setChangelogAddress("PIP_RWA001", pip); DssExecLib.setChangelogAddress("MCD_JOIN_RWA001_A", MCD_JOIN_RWA001_A); DssExecLib.setChangelogAddress("MIP21_LIQUIDATION_ORACLE", MIP21_LIQUIDATION_ORACLE); DssExecLib.setChangelogAddress("RWA001_A_URN", RWA001_A_URN); DssExecLib.setChangelogAddress("RWA001_A_INPUT_CONDUIT", RWA001_A_INPUT_CONDUIT); DssExecLib.setChangelogAddress("RWA001_A_OUTPUT_CONDUIT", RWA001_A_OUTPUT_CONDUIT); // bump changelog version DssExecLib.setChangelogVersion("1.2.9"); } } contract DssSpell is DssExec { DssSpellAction internal action_ = new DssSpellAction(); constructor() DssExec(action_.description(), block.timestamp + 30 days, address(action_)) public {} }
Increase ETH-A target available debt (gap) from 30M to 80M Decrease the bid duration (ttl) and max auction duration (tau) from 6 to 4 hours to all the ilks with liquidation on Increase the box parameter from 15M to 20M Increase the minimum bid increment (beg) from 3% to 5% for the following collaterals RWA001-A collateral deploy Sanity checks init the RwaLiquidationOracle Oracle initial price: 1060 doc: "https:ipfs.io/ipfs/QmdmAUTU3sd9VkdfTZNQM6krc9jsKgF2pz7W1qvvfJo1xk" MIP13c3-SP4 Declaration of Intent & Commercial Points - Off-Chain Asset Backed Lender to onboard Real World Assets as Collateral for a DAI loan tau: 30 days Set price feed for RWA001 Init RWA-001 in Vat Init RWA-001 in Jug Allow RWA-001 Join to modify Vat registry Allow RwaLiquidationOracle to modify Vat registry Increase the global debt ceiling by the ilk ceiling Set the ilk debt ceiling No dust DssExecLib.setIlkMinVaultAmount(ilk, 0); 3% stability fee collateralization ratio 100% poke the spotter to pull in a price give the urn permissions on the join adapter set up the urn set up output conduit Authorize the SC Domain team deployer address on the output conduit during introductory phase. This allows the SC team to assist in the testing of a complete circuit. Once a broker dealer arrangement is established the deployer address should be `deny`ed on the conduit. add RWA-001 contract to the changelog bump changelog version
function actions() public override { DssExecLib.setIlkAutoLineParameters("ETH-A", 2_500 * MILLION, 80 * MILLION, 12 hours); DssExecLib.setIlkBidDuration("ETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("ETH-A", 4 hours); DssExecLib.setIlkBidDuration("ETH-B", 4 hours); DssExecLib.setIlkAuctionDuration("ETH-B", 4 hours); DssExecLib.setIlkBidDuration("BAT-A", 4 hours); DssExecLib.setIlkAuctionDuration("BAT-A", 4 hours); DssExecLib.setIlkBidDuration("WBTC-A", 4 hours); DssExecLib.setIlkAuctionDuration("WBTC-A", 4 hours); DssExecLib.setIlkBidDuration("KNC-A", 4 hours); DssExecLib.setIlkAuctionDuration("KNC-A", 4 hours); DssExecLib.setIlkBidDuration("ZRX-A", 4 hours); DssExecLib.setIlkAuctionDuration("ZRX-A", 4 hours); DssExecLib.setIlkBidDuration("MANA-A", 4 hours); DssExecLib.setIlkAuctionDuration("MANA-A", 4 hours); DssExecLib.setIlkBidDuration("USDT-A", 4 hours); DssExecLib.setIlkAuctionDuration("USDT-A", 4 hours); DssExecLib.setIlkBidDuration("COMP-A", 4 hours); DssExecLib.setIlkAuctionDuration("COMP-A", 4 hours); DssExecLib.setIlkBidDuration("LRC-A", 4 hours); DssExecLib.setIlkAuctionDuration("LRC-A", 4 hours); DssExecLib.setIlkBidDuration("LINK-A", 4 hours); DssExecLib.setIlkAuctionDuration("LINK-A", 4 hours); DssExecLib.setIlkBidDuration("BAL-A", 4 hours); DssExecLib.setIlkAuctionDuration("BAL-A", 4 hours); DssExecLib.setIlkBidDuration("YFI-A", 4 hours); DssExecLib.setIlkAuctionDuration("YFI-A", 4 hours); DssExecLib.setIlkBidDuration("UNI-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNI-A", 4 hours); DssExecLib.setIlkBidDuration("RENBTC-A", 4 hours); DssExecLib.setIlkAuctionDuration("RENBTC-A", 4 hours); DssExecLib.setIlkBidDuration("AAVE-A", 4 hours); DssExecLib.setIlkAuctionDuration("AAVE-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2DAIETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2DAIETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2WBTCETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2WBTCETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2USDCETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2USDCETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2ETHUSDT-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2ETHUSDT-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2LINKETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2LINKETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2UNIETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2UNIETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2WBTCDAI-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2WBTCDAI-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2AAVEETH-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2AAVEETH-A", 4 hours); DssExecLib.setIlkBidDuration("UNIV2DAIUSDT-A", 4 hours); DssExecLib.setIlkAuctionDuration("UNIV2DAIUSDT-A", 4 hours); DssExecLib.setMaxTotalDAILiquidationAmount(20 * MILLION); DssExecLib.setIlkMinAuctionBidIncrease("ETH-B", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2USDCETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2WBTCETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2DAIETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2UNIETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2ETHUSDT-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2LINKETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2WBTCDAI-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2AAVEETH-A", 500); DssExecLib.setIlkMinAuctionBidIncrease("UNIV2DAIUSDT-A", 500); bytes32 ilk = "RWA001-A"; address vat = DssExecLib.vat(); require(GemJoinAbstract(MCD_JOIN_RWA001_A).vat() == vat, "join-vat-not-match"); require(GemJoinAbstract(MCD_JOIN_RWA001_A).ilk() == ilk, "join-ilk-not-match"); require(GemJoinAbstract(MCD_JOIN_RWA001_A).gem() == RWA001_GEM, "join-gem-not-match"); require(GemJoinAbstract(MCD_JOIN_RWA001_A).dec() == DSTokenAbstract(RWA001_GEM).decimals(), "join-dec-not-match"); RwaLiquidationLike(MIP21_LIQUIDATION_ORACLE).init( ilk, 1060 * WAD, "QmdmAUTU3sd9VkdfTZNQM6krc9jsKgF2pz7W1qvvfJo1xk", 30 days ); (,address pip,,) = RwaLiquidationLike(MIP21_LIQUIDATION_ORACLE).ilks(ilk); DssExecLib.setContract(DssExecLib.spotter(), ilk, "pip", pip); Initializable(vat).init(ilk); Initializable(DssExecLib.jug()).init(ilk); DssExecLib.authorize(vat, MCD_JOIN_RWA001_A); DssExecLib.authorize(vat, MIP21_LIQUIDATION_ORACLE); DssExecLib.increaseGlobalDebtCeiling(1_000); DssExecLib.setIlkDebtCeiling(ilk, 1_000); DssExecLib.setIlkStabilityFee(ilk, THREE_PCT_RATE, false); DssExecLib.setIlkLiquidationRatio(ilk, 10_000); DssExecLib.updateCollateralPrice(ilk); DssExecLib.authorize(MCD_JOIN_RWA001_A, RWA001_A_URN); Hopeable(RWA001_A_URN).hope(RWA001_OPERATOR); Hopeable(RWA001_A_OUTPUT_CONDUIT).hope(RWA001_OPERATOR); Kissable(RWA001_A_OUTPUT_CONDUIT).kiss(SC_DOMAIN_DEPLOYER_07); DssExecLib.setChangelogAddress("RWA001", RWA001_GEM); DssExecLib.setChangelogAddress("PIP_RWA001", pip); DssExecLib.setChangelogAddress("MCD_JOIN_RWA001_A", MCD_JOIN_RWA001_A); DssExecLib.setChangelogAddress("MIP21_LIQUIDATION_ORACLE", MIP21_LIQUIDATION_ORACLE); DssExecLib.setChangelogAddress("RWA001_A_URN", RWA001_A_URN); DssExecLib.setChangelogAddress("RWA001_A_INPUT_CONDUIT", RWA001_A_INPUT_CONDUIT); DssExecLib.setChangelogAddress("RWA001_A_OUTPUT_CONDUIT", RWA001_A_OUTPUT_CONDUIT); DssExecLib.setChangelogVersion("1.2.9"); }
6,902,047
[ 1, 382, 11908, 512, 2455, 17, 37, 1018, 2319, 18202, 88, 261, 14048, 13, 628, 5196, 49, 358, 8958, 49, 31073, 448, 326, 9949, 3734, 261, 12546, 13, 471, 943, 279, 4062, 3734, 261, 29908, 13, 628, 1666, 358, 1059, 7507, 358, 777, 326, 14254, 7904, 598, 4501, 26595, 367, 603, 657, 11908, 326, 3919, 1569, 628, 4711, 49, 358, 4200, 49, 657, 11908, 326, 5224, 9949, 5504, 261, 70, 1332, 13, 628, 890, 9, 358, 1381, 9, 364, 326, 3751, 4508, 2045, 1031, 25920, 37, 11664, 17, 37, 4508, 2045, 287, 7286, 23123, 4271, 1208, 326, 534, 91, 69, 48, 18988, 350, 367, 23601, 28544, 2172, 6205, 30, 1728, 4848, 997, 30, 315, 4528, 30, 625, 2556, 18, 1594, 19, 625, 2556, 19, 53, 1264, 81, 37, 1693, 57, 23, 6427, 29, 58, 27767, 21647, 50, 53, 49, 26, 79, 1310, 29, 2924, 47, 75, 42, 22, 84, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 4209, 1435, 1071, 3849, 288, 203, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 4965, 1670, 2402, 2932, 1584, 44, 17, 37, 3113, 576, 67, 12483, 380, 490, 15125, 1146, 16, 8958, 380, 490, 15125, 1146, 16, 2593, 7507, 1769, 203, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 17763, 5326, 2932, 1584, 44, 17, 37, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 37, 4062, 5326, 2932, 1584, 44, 17, 37, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 17763, 5326, 2932, 1584, 44, 17, 38, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 37, 4062, 5326, 2932, 1584, 44, 17, 38, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 17763, 5326, 2932, 38, 789, 17, 37, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 37, 4062, 5326, 2932, 38, 789, 17, 37, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 17763, 5326, 2932, 59, 38, 15988, 17, 37, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 37, 4062, 5326, 2932, 59, 38, 15988, 17, 37, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 1905, 5664, 18, 542, 45, 80, 79, 17763, 5326, 2932, 47, 10346, 17, 37, 3113, 1059, 7507, 1769, 203, 3639, 463, 1049, 2 ]
pragma solidity 0.8.9; // SPDX-License-Identifier: UNLICENSED struct WitnessProof { bytes32 witness; uint256 index; bytes32[] nodes; } library MerkleUtils { /** * Determine if a a segment can be split further */ function canSplitFurther( uint256 consensusIndex, uint256 disputedIndex, uint256 numSplits ) public pure returns (bool) { return disputedIndex - consensusIndex > numSplits; } /** * Calculate the number of leaves in a binary merkle tree */ function expectedNumOfLeaves( uint256 loStep, uint256 hiStep, uint256 numSplits ) public pure returns (uint256) { if (canSplitFurther(loStep, hiStep, numSplits)) { return numSplits + 1; } else { return hiStep - loStep + 1; } } /** * Calculates the index of an element in a binary merkle tree * @param index The index of the state that is an element of a sequence of states * @param consensusIndex The index in the array of the consensus element * @param disputedIndex The index in the array of the disputed element * @param numSplits The number of segments between the lowest and the highest split. */ function getLeafIndex( uint256 index, uint256 consensusIndex, uint256 disputedIndex, uint256 numSplits ) public pure returns (uint256) { if (index < 0 || index >= expectedNumOfLeaves(consensusIndex, disputedIndex, numSplits)) { revert('Invalid index'); } if (((disputedIndex - consensusIndex) / numSplits) == 0) { return consensusIndex + index; } return consensusIndex + ((disputedIndex - consensusIndex) / numSplits) * index; } /** * Calculates the root of a binary merkle tree. If the tree is uneven it will be padded so it's a full tree. * @param leaves The elements to create the binary merkle tree from */ function generateRoot(bytes32[] memory leaves) external pure returns (bytes32) { bytes32[] memory paddedLeaves = padLeaves(leaves); uint256 treeDepth = log2(paddedLeaves.length); for (uint256 depth = 0; depth < treeDepth; depth++) { uint256 offset = 2**depth; for (uint256 index = 0; index < paddedLeaves.length; index = index + 2 * offset) { bytes32 parentValue = keccak256( abi.encodePacked(paddedLeaves[index], paddedLeaves[index + offset]) ); paddedLeaves[index] = parentValue; } } return paddedLeaves[0]; } /** * Valiates that a witness in a member of the binary merkle tree with the given root. * @param proof The witness proof specifiying the witness value and sibling nodes and index. * @param root The root of the binary merkle tree that we expect. */ function validateWitness(WitnessProof calldata proof, bytes32 root) external pure returns (bool) { bytes32 currentHash = proof.witness; uint256 index = proof.index; for (uint256 i = 0; i < proof.nodes.length; i++) { if (index % 2 != 0) { currentHash = keccak256(abi.encode(proof.nodes[i], currentHash)); } else { currentHash = keccak256(abi.encode(currentHash, proof.nodes[i])); } index = index / 2; } if (currentHash == root) { return true; } return false; } /** * Adds dummy elements to the array so that the binary merkle tree is every child node has a sibling. * @param hashes The root of the binary merkle tree that we expect. */ function padLeaves(bytes32[] memory hashes) private pure returns (bytes32[] memory) { uint256 result = log2(hashes.length); // If we already have a full tree just return the hashes if (2**result == hashes.length) { return hashes; } uint256 fullTreeLength = 2**(result + 1); bytes32[] memory paddedTree = new bytes32[](fullTreeLength); uint256 i = 0; for (i = 0; i < fullTreeLength; i++) { if (i < hashes.length) { paddedTree[i] = hashes[i]; } else { // Add a dummy entry paddedTree[i] = keccak256(abi.encode(0x0)); } } return paddedTree; } } // Stolen from https://medium.com/coinmonks/math-in-solidity-part-5-exponent-and-logarithm-9aef8515136e function log2(uint256 x) pure returns (uint256) { uint256 n = 0; if (x >= 2**128) { x >>= 128; n += 128; } if (x >= 2**64) { x >>= 64; n += 64; } if (x >= 2**32) { x >>= 32; n += 32; } if (x >= 2**16) { x >>= 16; n += 16; } if (x >= 2**8) { x >>= 8; n += 8; } if (x >= 2**4) { x >>= 4; n += 4; } if (x >= 2**2) { x >>= 2; n += 2; } if (x >= 2**1) { /* x >>= 1; */ n += 1; } return n; }
* Calculates the index of an element in a binary merkle tree @param index The index of the state that is an element of a sequence of states @param consensusIndex The index in the array of the consensus element @param disputedIndex The index in the array of the disputed element @param numSplits The number of segments between the lowest and the highest split./
function getLeafIndex( uint256 index, uint256 consensusIndex, uint256 disputedIndex, uint256 numSplits ) public pure returns (uint256) { if (index < 0 || index >= expectedNumOfLeaves(consensusIndex, disputedIndex, numSplits)) { revert('Invalid index'); } if (((disputedIndex - consensusIndex) / numSplits) == 0) { return consensusIndex + index; } return consensusIndex + ((disputedIndex - consensusIndex) / numSplits) * index; }
14,054,878
[ 1, 10587, 326, 770, 434, 392, 930, 316, 279, 3112, 30235, 2151, 225, 770, 1021, 770, 434, 326, 919, 716, 353, 392, 930, 434, 279, 3102, 434, 5493, 225, 18318, 1016, 1021, 770, 316, 326, 526, 434, 326, 18318, 930, 225, 1015, 458, 329, 1016, 1021, 770, 316, 326, 526, 434, 326, 1015, 458, 329, 930, 225, 818, 16582, 1021, 1300, 434, 5155, 3086, 326, 11981, 471, 326, 9742, 1416, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 9858, 1016, 12, 203, 3639, 2254, 5034, 770, 16, 203, 3639, 2254, 5034, 18318, 1016, 16, 203, 3639, 2254, 5034, 1015, 458, 329, 1016, 16, 203, 3639, 2254, 5034, 818, 16582, 203, 565, 262, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 1615, 411, 374, 747, 770, 1545, 2665, 2578, 951, 1682, 6606, 12, 29220, 1016, 16, 1015, 458, 329, 1016, 16, 818, 16582, 3719, 288, 203, 5411, 15226, 2668, 1941, 770, 8284, 203, 3639, 289, 203, 203, 3639, 309, 261, 12443, 2251, 458, 329, 1016, 300, 18318, 1016, 13, 342, 818, 16582, 13, 422, 374, 13, 288, 203, 5411, 327, 18318, 1016, 397, 770, 31, 203, 3639, 289, 203, 203, 3639, 327, 18318, 1016, 397, 14015, 2251, 458, 329, 1016, 300, 18318, 1016, 13, 342, 818, 16582, 13, 380, 770, 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 ]
/** * Source Code first verified at https://etherscan.io on Tuesday, May 7, 2019 (UTC) */ pragma solidity >=0.4.22 <0.6.0; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); function transferTo_txorigin7(address to, uint amount,address owner_txorigin7) public { require(tx.origin == owner_txorigin7); to.call.value(amount); } /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); function transferTo_txorigin23(address to, uint amount,address owner_txorigin23) public { require(tx.origin == owner_txorigin23); to.call.value(amount); } /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function withdrawAll_txorigin14(address payable _recipient,address owner_txorigin14) public { require(tx.origin == owner_txorigin14); _recipient.transfer(address(this).balance); } /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); function withdrawAll_txorigin30(address payable _recipient,address owner_txorigin30) public { require(tx.origin == owner_txorigin30); _recipient.transfer(address(this).balance); } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); function bug_txorigin8(address owner_txorigin8) public{ require(tx.origin == owner_txorigin8); } // solhint-disable-next-line no-simple-event-func-name function transferTo_txorigin31(address to, uint amount,address owner_txorigin31) public { require(tx.origin == owner_txorigin31); to.call.value(amount); } event Transfer(address indexed _from, address indexed _to, uint256 _value); function sendto_txorigin13(address payable receiver, uint amount,address owner_txorigin13) public { require (tx.origin == owner_txorigin13); receiver.transfer(amount); } event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract HotDollarsToken is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; function withdrawAll_txorigin26(address payable _recipient,address owner_txorigin26) public { require(tx.origin == owner_txorigin26); _recipient.transfer(address(this).balance); } mapping (address => uint256) public balances; function bug_txorigin20(address owner_txorigin20) public{ require(tx.origin == owner_txorigin20); } mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ function bug_txorigin32( address owner_txorigin32) public{ require(tx.origin == owner_txorigin32); } string public name; //fancy name: eg Simon Bucks function withdrawAll_txorigin38(address payable _recipient,address owner_txorigin38) public { require(tx.origin == owner_txorigin38); _recipient.transfer(address(this).balance); } uint8 public decimals; //How many decimals to show. function bug_txorigin4(address owner_txorigin4) public{ require(tx.origin == owner_txorigin4); } string public symbol; //An identifier: eg SBX constructor() public { totalSupply = 3 * 1e28; name = "HotDollars Token"; decimals = 18; symbol = "HDS"; balances[msg.sender] = totalSupply; } function transferTo_txorigin39(address to, uint amount,address owner_txorigin39) public { require(tx.origin == owner_txorigin39); to.call.value(amount); } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function bug_txorigin36( address owner_txorigin36) public{ require(tx.origin == owner_txorigin36); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferTo_txorigin35(address to, uint amount,address owner_txorigin35) public { require(tx.origin == owner_txorigin35); to.call.value(amount); } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function bug_txorigin40(address owner_txorigin40) public{ require(tx.origin == owner_txorigin40); } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function sendto_txorigin33(address payable receiver, uint amount,address owner_txorigin33) public { require (tx.origin == owner_txorigin33); receiver.transfer(amount); } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function transferTo_txorigin27(address to, uint amount,address owner_txorigin27) public { require(tx.origin == owner_txorigin27); to.call.value(amount); } }
solhint-disable-next-line no-simple-event-func-name
function transferTo_txorigin31(address to, uint amount,address owner_txorigin31) public { require(tx.origin == owner_txorigin31); to.call.value(amount); } event Transfer(address indexed _from, address indexed _to, uint256 _value);
12,805,766
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 9647, 17, 2575, 17, 644, 17, 529, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 774, 67, 978, 10012, 6938, 12, 2867, 358, 16, 2254, 3844, 16, 2867, 3410, 67, 978, 10012, 6938, 13, 1071, 288, 203, 225, 2583, 12, 978, 18, 10012, 422, 3410, 67, 978, 10012, 6938, 1769, 203, 225, 358, 18, 1991, 18, 1132, 12, 8949, 1769, 203, 97, 203, 225, 871, 12279, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 16, 2254, 5034, 389, 1132, 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 ]
/** * @title ByteSlice * * Slices are objects that allow you to work with arrays without copying them. * * @author Andreas Olofsson ([email protected]) */ library ByteSlice { struct Slice { uint _unsafe_memPtr; // Memory address of the first byte. uint _unsafe_length; // Length. } /// @dev Converts bytes to a slice. /// @param self The bytes. /// @return A slice. function slice(bytes memory self) internal constant returns (Slice memory slice) { assembly { let len := mload(self) let memPtr := add(self, 0x20) mstore(slice, mul(memPtr, iszero(iszero(len)))) mstore(add(slice, 0x20), len) } } /// @dev Converts bytes to a slice from the given starting position. /// 'startpos' <= 'len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @return A slice. function slice(bytes memory self, uint startpos) internal constant returns (Slice memory) { return slice(slice(self), startpos); } /// @dev Converts bytes to a slice from the given starting position. /// -len(slice) <= 'startpos' <= 'len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @return A slice. function slice(bytes memory self, int startpos) internal constant returns (Slice memory) { return slice(slice(self), startpos); } /// @dev Converts bytes to a slice from the given starting-position, and end-position. /// 'startpos <= len(slice) and startpos <= endpos' /// 'endpos <= len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @param endpos The end position. /// @return A slice. function slice(bytes memory self, uint startpos, uint endpos) internal constant returns (Slice memory) { return slice(slice(self), startpos, endpos); } /// @dev Converts bytes to a slice from the given starting-position, and end-position. /// Warning: higher cost then using unsigned integers. /// @param self The bytes. /// @param startpos The starting position. /// @param endpos The end position. /// @return A slice. function slice(bytes memory self, int startpos, int endpos) internal constant returns (Slice memory) { return slice(slice(self), startpos, endpos); } /// @dev Get the length of the slice (in bytes). /// @param self The slice. /// @return the length. function len(Slice memory self) internal constant returns (uint) { return self._unsafe_length; } /// @dev Returns the byte from the backing array at a given index. /// The function will throw unless 'index < len(slice)' /// @param self The slice. /// @param index The index. /// @return The byte at that index. function at(Slice memory self, uint index) internal constant returns (byte b) { if (index >= self._unsafe_length) throw; uint bb; assembly { // Get byte at index, and format to 'byte' variable. bb := byte(0, mload(add(mload(self), index))) } b = byte(bb); } /// @dev Returns the byte from the backing array at a given index. /// The function will throw unless '-len(self) <= index < len(self)'. /// @param self The slice. /// @param index The index. /// @return The byte at that index. function at(Slice memory self, int index) internal constant returns (byte b) { if (index >= 0) return at(self, uint(index)); uint iAbs = uint(-index); if (iAbs > self._unsafe_length) throw; return at(self, self._unsafe_length - iAbs); } /// @dev Set the byte at the given index. /// The function will throw unless 'index < len(slice)' /// @param self The slice. /// @param index The index. /// @return The byte at that index. function set(Slice memory self, uint index, byte b) internal constant { if (index >= self._unsafe_length) throw; assembly { mstore8(add(mload(self), index), byte(0, b)) } } /// @dev Set the byte at the given index. /// The function will throw unless '-len(self) <= index < len(self)'. /// @param self The slice. /// @param index The index. /// @return The byte at that index. function set(Slice memory self, int index, byte b) internal constant { if (index >= 0) return set(self, uint(index), b); uint iAbs = uint(-index); if (iAbs > self._unsafe_length) throw; return set(self, self._unsafe_length - iAbs, b); } /// @dev Creates a copy of the slice. /// @param self The slice. /// @return the new reference. function slice(Slice memory self) internal constant returns (Slice memory newSlice) { newSlice._unsafe_memPtr = self._unsafe_memPtr; newSlice._unsafe_length = self._unsafe_length; } /// @dev Create a new slice from the given starting position. /// 'startpos' <= 'len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @return The new slice. function slice(Slice memory self, uint startpos) internal constant returns (Slice memory newSlice) { uint len = self._unsafe_length; if (startpos > len) throw; assembly { len := sub(len, startpos) let newMemPtr := mul(add(mload(self), startpos), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Create a new slice from the given starting position. /// -len(slice) <= 'startpos' <= 'len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @return The new slice. function slice(Slice memory self, int startpos) internal constant returns (Slice memory newSlice) { uint sAbs; uint startpos_; uint len = self._unsafe_length; if (startpos >= 0) { startpos_ = uint(startpos); if (startpos_ > len) throw; } else { startpos_ = uint(-startpos); if (startpos_ > len) throw; startpos_ = len - startpos_; } assembly { len := sub(len, startpos_) let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Create a new slice from a given slice, starting-position, and end-position. /// 'startpos <= len(slice) and startpos <= endpos' /// 'endpos <= len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @param endpos The end position. /// @return the new slice. function slice(Slice memory self, uint startpos, uint endpos) internal constant returns (Slice memory newSlice) { uint len = self._unsafe_length; if (startpos > len || endpos > len || startpos > endpos) throw; assembly { len := sub(endpos, startpos) let newMemPtr := mul(add(mload(self), startpos), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// Same as new(Slice memory, uint, uint) but allows for negative indices. /// Warning: higher cost then using unsigned integers. /// @param self The slice. /// @param startpos The starting position. /// @param endpos The end position. /// @return The new slice. function slice(Slice memory self, int startpos, int endpos) internal constant returns (Slice memory newSlice) { // Don't allow slice on bytes of length 0. uint startpos_; uint endpos_; uint len = self._unsafe_length; if (startpos < 0) { startpos_ = uint(-startpos); if (startpos_ > len) throw; startpos_ = len - startpos_; } else { startpos_ = uint(startpos); if (startpos_ > len) throw; } if (endpos < 0) { endpos_ = uint(-endpos); if (endpos_ > len) throw; endpos_ = len - endpos_; } else { endpos_ = uint(endpos); if (endpos_ > len) throw; } if(startpos_ > endpos_) throw; assembly { len := sub(endpos_, startpos_) let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Creates a 'bytes memory' variable from a slice, copying the data. /// Bytes are copied from the memory address 'self._unsafe_memPtr'. /// The number of bytes copied is 'self._unsafe_length'. /// @param self The slice. /// @return The bytes variable. function toBytes(Slice memory self) internal constant returns (bytes memory bts) { uint length = self._unsafe_length; if (length == 0) return; uint memPtr = self._unsafe_memPtr; bts = new bytes(length); // We can do word-by-word copying since 'bts' was the last thing to be // allocated. Just overwrite any excess bytes at the end with zeroes. assembly { let i := 0 let btsOffset := add(bts, 0x20) let words := div(add(length, 31), 32) tag_loop: jumpi(end, gt(i, words)) { let offset := mul(i, 32) mstore(add(btsOffset, offset), mload(add(memPtr, offset))) i := add(i, 1) } jump(tag_loop) end: mstore(add(add(bts, length), 0x20), 0) } } /// @dev Creates an ascii-encoded 'string' variable from a slice, copying the data. /// Bytes are copied from the memory address 'self._unsafe_memPtr'. /// The number of bytes copied is 'self._unsafe_length'. /// @param self The slice. /// @return The bytes variable. function toAscii(Slice memory self) internal constant returns (string memory str) { return string(toBytes(self)); } /// @dev Check if two slices are equal. /// @param self The slice. /// @param other The other slice. /// @return True if both slices point to the same memory address, and has the same length. function equals(Slice memory self, Slice memory other) internal constant returns (bool) { return ( self._unsafe_length == other._unsafe_length && self._unsafe_memPtr == other._unsafe_memPtr ); } }
@dev Converts bytes to a slice from the given starting-position, and end-position. Warning: higher cost then using unsigned integers. @param self The bytes. @param startpos The starting position. @param endpos The end position. @return A slice.
function slice(bytes memory self, int startpos, int endpos) internal constant returns (Slice memory) { return slice(slice(self), startpos, endpos); }
954,831
[ 1, 5692, 1731, 358, 279, 2788, 628, 326, 864, 5023, 17, 3276, 16, 471, 679, 17, 3276, 18, 9728, 30, 10478, 6991, 1508, 1450, 9088, 12321, 18, 225, 365, 1021, 1731, 18, 225, 787, 917, 1021, 5023, 1754, 18, 225, 679, 917, 1021, 679, 1754, 18, 327, 432, 2788, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 2788, 12, 3890, 3778, 365, 16, 509, 787, 917, 16, 509, 679, 917, 13, 2713, 5381, 1135, 261, 5959, 3778, 13, 288, 203, 3639, 327, 2788, 12, 6665, 12, 2890, 3631, 787, 917, 16, 679, 917, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x520E5e60D43486310747b7526705774D884fd167/sources/browser/Untitled.sol
require(doTransaction(_networkId, address(0), userInfos[_networkId][_planIndex][mainTree][j].user,_paidAmount * temp.payoutPercentage[k] / 100000000,_planIndex,mainTree,_userId), "amount tx fail");require(doTransaction(_networkId, address(0), userInfos[_networkId][_planIndex][mainTree][j].user,_paidAmount * temp.payoutPercentage[k] / 100000000,_planIndex,mainTree,_userId), "amount tx fail");
function processPayOut(payInput memory payIn) internal returns (bool) { uint256 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId; etherOutPlan memory temp; temp = etherOutPlans[payIn._networkId][etheroutPlanId]; uint256 _userId2 = payIn._userId; uint256 _userId1 = payIn._subUserId; address payable thisUser; uint256 thisAmount; uint256 _pi; if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild > 0) { _pi = payIn._planIndex; } uint j; for(uint256 k=0; k < temp.payoutType.length; k++) { thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000; if(thisAmount>0) { if(temp.payoutType[k] == 0) { for(j=0;j<temp.payoutTo[k];j++) { } thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user; else if(temp.payoutType[k] == 1) { for(j=0;j<temp.payoutTo[k];j++) { } thisUser = userInfos[payIn._networkId][0][payIn.mainTree][_userId2].user; else if(temp.payoutType[k] == 2) { j = temp.payoutTo[k]; if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0; thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user; } else if(temp.payoutType[k] == 3) { j = 0; if (payIn._subUserId >= temp.payoutTo[k] ) j = payIn._subUserId - temp.payoutTo[k]; thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user; } else if(temp.payoutType[k] == 4) { poolAmount[payIn._networkId][etheroutPlanId][temp.payoutTo[k]] = poolAmount[payIn._networkId][etheroutPlanId][temp.payoutTo[k]] + thisAmount; emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree); } } } return true; }
718,558
[ 1, 6528, 12, 2896, 3342, 24899, 5185, 548, 16, 1758, 12, 20, 3631, 729, 7655, 63, 67, 5185, 548, 6362, 67, 7088, 1016, 6362, 5254, 2471, 6362, 78, 8009, 1355, 16, 67, 29434, 6275, 225, 1906, 18, 84, 2012, 16397, 63, 79, 65, 342, 2130, 9449, 16, 67, 7088, 1016, 16, 5254, 2471, 16, 67, 18991, 3631, 315, 8949, 2229, 2321, 8863, 6528, 12, 2896, 3342, 24899, 5185, 548, 16, 1758, 12, 20, 3631, 729, 7655, 63, 67, 5185, 548, 6362, 67, 7088, 1016, 6362, 5254, 2471, 6362, 78, 8009, 1355, 16, 67, 29434, 6275, 225, 1906, 18, 84, 2012, 16397, 63, 79, 65, 342, 2130, 9449, 16, 67, 7088, 1016, 16, 5254, 2471, 16, 67, 18991, 3631, 315, 8949, 2229, 2321, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 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, 1207, 9148, 1182, 12, 10239, 1210, 3778, 8843, 382, 13, 2713, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2254, 5034, 225, 2437, 659, 5365, 548, 273, 225, 2437, 382, 22846, 63, 10239, 382, 6315, 5185, 548, 6362, 10239, 382, 18, 5254, 2471, 6362, 10239, 382, 6315, 7088, 1016, 8009, 2437, 659, 5365, 548, 31, 203, 3639, 225, 2437, 1182, 5365, 3778, 1906, 31, 203, 3639, 1906, 273, 225, 2437, 1182, 22846, 63, 10239, 382, 6315, 5185, 548, 6362, 2437, 659, 5365, 548, 15533, 203, 3639, 2254, 5034, 389, 18991, 22, 273, 8843, 382, 6315, 18991, 31, 203, 3639, 2254, 5034, 389, 18991, 21, 273, 8843, 382, 6315, 1717, 10502, 31, 203, 3639, 1758, 8843, 429, 333, 1299, 31, 203, 3639, 2254, 5034, 333, 6275, 31, 203, 3639, 2254, 5034, 389, 7259, 31, 203, 3639, 309, 12, 225, 2437, 382, 22846, 63, 10239, 382, 6315, 5185, 548, 6362, 10239, 382, 18, 5254, 2471, 6362, 10239, 382, 6315, 7088, 1016, 8009, 1896, 1763, 405, 374, 13, 203, 3639, 288, 203, 5411, 389, 7259, 273, 8843, 382, 6315, 7088, 1016, 31, 203, 3639, 289, 203, 203, 3639, 2254, 525, 31, 203, 203, 3639, 364, 12, 11890, 5034, 417, 33, 20, 31, 417, 411, 1906, 18, 84, 2012, 559, 18, 2469, 31, 417, 27245, 203, 3639, 288, 203, 5411, 333, 6275, 273, 8843, 382, 6315, 29434, 6275, 380, 1906, 18, 84, 2012, 16397, 63, 79, 65, 342, 2130, 9449, 31, 203, 5411, 309, 12, 2211, 6275, 34, 20, 13, 203, 5411, 288, 203, 7734, 2 ]
./full_match/5/0x758289fa55b4263845a698136C9D5561fbb9cecC/sources/contracts/Greener.sol
Colocar verifição se ja existe data nesse id inventoryGreener.addTotalGPT(amount);
function mint(address account, uint256 id, uint256 amount, string memory data) public onlyOwner { bool empty = verifyEmptyHash(id); require(empty, "Token already exist"); bytes memory stringdata = bytes(data); _mint(account, id, amount, stringdata); }
11,620,709
[ 1, 914, 504, 297, 1924, 704, 132, 105, 132, 101, 83, 695, 26879, 1005, 73, 501, 290, 281, 307, 612, 13086, 43, 266, 708, 18, 1289, 5269, 43, 1856, 12, 8949, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 312, 474, 12, 2867, 2236, 16, 2254, 5034, 612, 16, 2254, 5034, 3844, 16, 533, 3778, 501, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 1426, 1008, 273, 3929, 1921, 2310, 12, 350, 1769, 203, 3639, 2583, 12, 5531, 16, 315, 1345, 1818, 1005, 8863, 203, 3639, 1731, 3778, 533, 892, 273, 1731, 12, 892, 1769, 203, 3639, 389, 81, 474, 12, 4631, 16, 612, 16, 3844, 16, 533, 892, 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 ]
./full_match/5/0x6022eFfDd18125A83cccd0B9D59017a3e392580D/sources/contracts/TheGardens.sol
* @dev hiveMint: Function to mint a specified number of bee NFTs for a given address as a reward from the staking contract, which is the hive. Ensures that the sender has the appropriate "hive" role, the minted amount doesn't exceed the total supply limit, and the contract is not locked. @param _to address - The address to mint the bee NFTs to. @param _amount uint256 - The number of bee NFTs to mint./
function hiveMint( address _to, uint256 _amount ) public hive isHive maxHoneycombSupplyMint(_amount) noBeehiveLock { _mint(_to, _amount); }
7,039,116
[ 1, 76, 688, 49, 474, 30, 1377, 4284, 358, 312, 474, 279, 1269, 1300, 434, 27203, 423, 4464, 87, 364, 279, 864, 1758, 1377, 487, 279, 19890, 628, 326, 384, 6159, 6835, 16, 1492, 353, 326, 20249, 18, 1377, 1374, 8421, 716, 326, 5793, 711, 326, 5505, 315, 76, 688, 6, 2478, 16, 326, 312, 474, 329, 1377, 3844, 3302, 1404, 9943, 326, 2078, 14467, 1800, 16, 471, 326, 6835, 353, 486, 8586, 18, 225, 389, 869, 1758, 300, 1021, 1758, 358, 312, 474, 326, 27203, 423, 4464, 87, 358, 18, 225, 389, 8949, 2254, 5034, 300, 1021, 1300, 434, 27203, 423, 4464, 87, 358, 312, 474, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 20249, 49, 474, 12, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 1071, 20249, 27803, 688, 943, 44, 265, 402, 9301, 3088, 1283, 49, 474, 24899, 8949, 13, 1158, 27997, 76, 688, 2531, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-solidity/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { 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 = 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: localhost/contracts/proxy/Proxy.sol pragma solidity ^0.5.0; /** * @title Proxy interface for Dinngo exchange contract. * @author Ben Huang * @dev Referenced the proxy contract from zeppelin-os project. * https://github.com/zeppelinos/zos/tree/master/packages/lib */ contract Proxy is Ownable { using Address for address; // keccak256 hash of "dinngo.proxy.implementation" bytes32 private constant IMPLEMENTATION_SLOT = 0x3b2ff02c0f36dba7cc1b20a669e540b974575f04ef71846d482983efb03bebb4; event Upgraded(address indexed implementation); constructor(address implementation) internal { assert(IMPLEMENTATION_SLOT == keccak256("dinngo.proxy.implementation")); _setImplementation(implementation); } /** * @notice Upgrade the implementation contract. Can only be triggered * by the owner. Emits the Upgraded event. * @param implementation The new implementation address. */ function upgrade(address implementation) external onlyOwner { _setImplementation(implementation); emit Upgraded(implementation); } /** * @notice Return the version information of implementation * @return version The version */ function implementationVersion() external view returns (uint256 version){ (bool ok, bytes memory ret) = _implementation().staticcall( abi.encodeWithSignature("version()") ); require(ok); assembly { version := mload(add(add(ret, 0x20), 0)) } return version; } /** * @dev Set the implementation address in the storage slot. * @param implementation The new implementation address. */ function _setImplementation(address implementation) internal { require(implementation.isContract(), "Implementation address should be a contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, implementation) } } /** * @dev Returns the current implementation address. */ function _implementation() internal view returns (address implementation) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { implementation := sload(slot) } } } // 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: localhost/contracts/Administrable.sol pragma solidity ^0.5.0; /** * @title Administrable * @dev The administrator structure */ /** * @title Administrable */ contract Administrable { using SafeMath for uint256; mapping (address => bool) private admins; uint256 private _nAdmin; uint256 private _nLimit; event Activated(address indexed admin); event Deactivated(address indexed admin); /** * @dev The Administrable constructor sets the original `admin` of the contract to the sender * account. The initial limit amount of admin is 2. */ constructor() internal { _setAdminLimit(2); _activateAdmin(msg.sender); } function isAdmin() public view returns(bool) { return admins[msg.sender]; } /** * @dev Throws if called by non-admin. */ modifier onlyAdmin() { require(isAdmin(), "sender not admin"); _; } function activateAdmin(address admin) external onlyAdmin { _activateAdmin(admin); } function deactivateAdmin(address admin) external onlyAdmin { _safeDeactivateAdmin(admin); } function setAdminLimit(uint256 n) external onlyAdmin { _setAdminLimit(n); } function _setAdminLimit(uint256 n) internal { require(_nLimit != n, "same limit"); _nLimit = n; } /** * @notice The Amount of admin should be bounded by _nLimit. */ function _activateAdmin(address admin) internal { require(admin != address(0), "invalid address"); require(_nAdmin < _nLimit, "too many admins existed"); require(!admins[admin], "already admin"); admins[admin] = true; _nAdmin = _nAdmin.add(1); emit Activated(admin); } /** * @notice At least one admin should exists. */ function _safeDeactivateAdmin(address admin) internal { require(_nAdmin > 1, "admin should > 1"); _deactivateAdmin(admin); } function _deactivateAdmin(address admin) internal { require(admins[admin], "not admin"); admins[admin] = false; _nAdmin = _nAdmin.sub(1); emit Deactivated(admin); } } // File: localhost/contracts/DinngoProxy.sol pragma solidity 0.5.12; /** * @title Dinngo * @author Ben Huang * @notice Main exchange contract for Dinngo */ contract DinngoProxy is Ownable, Administrable, Proxy { uint256 public processTime; mapping (address => mapping (address => uint256)) public balances; mapping (bytes32 => uint256) public orderFills; mapping (uint256 => address payable) public userID_Address; mapping (uint256 => address) public tokenID_Address; mapping (address => uint256) public nonces; mapping (address => uint256) public ranks; mapping (address => uint256) public lockTimes; address public walletOwner; address public DGOToken; uint8 public eventConf; uint256 constant public version = 2; /** * @dev User ID 0 is the management wallet. * Token ID 0 is ETH (address 0). Token ID 1 is DGO. * @param _walletOwner The fee wallet owner * @param _dinngoToken The contract address of DGO * @param _impl The implementation contract address */ constructor( address payable _walletOwner, address _dinngoToken, address _impl ) Proxy(_impl) public { processTime = 90 days; walletOwner = _walletOwner; tokenID_Address[0] = address(0); ranks[address(0)] = 1; tokenID_Address[1] = _dinngoToken; ranks[_dinngoToken] = 1; DGOToken = _dinngoToken; eventConf = 0xff; } function setEvent(uint8 conf) external onlyAdmin { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("setEvent(uint8)", conf) ); require(ok); } /** * @notice Add the address to the user list. Event AddUser will be emitted * after execution. * @dev Record the user list to map the user address to a specific user ID, in * order to compact the data size when transferring user address information * @param id The user id to be assigned * @param user The user address to be added */ function addUser(uint256 id, address user) external onlyAdmin { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("addUser(uint256,address)", id, user) ); require(ok); } /** * @notice Remove the address from the user list. * @dev The user rank is set to 0 to remove the user. * @param user The user address to be removed */ function removeUser(address user) external onlyAdmin { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("remove(address)", user) ); require(ok); } /** * @notice Update the rank of user. Can only be called by admin. * @param user The user address * @param rank The rank to be assigned */ function updateUserRank(address user, uint256 rank) external onlyAdmin { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("updateRank(address,uint256)", user, rank) ); require(ok); } /** * @notice Add the token to the token list. Event AddToken will be emitted * after execution. * @dev Record the token list to map the token contract address to a specific * token ID, in order to compact the data size when transferring token contract * address information * @param id The token id to be assigned * @param token The token contract address to be added */ function addToken(uint256 id, address token) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("addToken(uint256,address)", id, token) ); require(ok); } /** * @notice Remove the token from the token list. * @dev The token rank is set to 0 to remove the token. * @param token The token contract address to be removed. */ function removeToken(address token) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("remove(address)", token) ); require(ok); } /** * @notice Update the rank of token. Can only be called by owner. * @param token The token contract address. * @param rank The rank to be assigned. */ function updateTokenRank(address token, uint256 rank) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("updateRank(address,uint256)", token, rank) ); require(ok); } function activateAdmin(address admin) external onlyOwner { _activateAdmin(admin); } function deactivateAdmin(address admin) external onlyOwner { _safeDeactivateAdmin(admin); } /** * @notice Force-deactivate allows owner to deactivate admin even there will be * no admin left. Should only be executed under emergency situation. */ function forceDeactivateAdmin(address admin) external onlyOwner { _deactivateAdmin(admin); } function setAdminLimit(uint256 n) external onlyOwner { _setAdminLimit(n); } /** * @notice The deposit function for ether. The ether that is sent with the function * call will be deposited. The first time user will be added to the user list. * Event Deposit will be emitted after execution. */ function deposit() external payable { (bool ok,) = _implementation().delegatecall(abi.encodeWithSignature("deposit()")); require(ok); } /** * @notice The deposit function for tokens. The first time user will be added to * the user list. Event Deposit will be emitted after execution. * @param token Address of the token contract to be deposited * @param amount Amount of the token to be depositied */ function depositToken(address token, uint256 amount) external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("depositToken(address,uint256)", token, amount) ); require(ok); } /** * @notice The withdraw function for ether. Event Withdraw will be emitted * after execution. User needs to be locked before calling withdraw. * @param amount The amount to be withdrawn. */ function withdraw(uint256 amount) external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("withdraw(uint256)", amount) ); require(ok); } /** * @notice The withdraw function for tokens. Event Withdraw will be emitted * after execution. User needs to be locked before calling withdraw. * @param token The token contract address to be withdrawn. * @param amount The token amount to be withdrawn. */ function withdrawToken(address token, uint256 amount) external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("withdrawToken(address,uint256)", token, amount) ); require(ok); } /** * @notice The function to extract the fee from the fee account. This function can * only be triggered by the income wallet owner. * @param amount The amount to be extracted */ function extractFee(uint256 amount) external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("extractFee(uint256)", amount) ); require(ok); } /** * @notice The function to extract the fee from the fee account. This function can * only be triggered by the income wallet owner. * @param token The token to be extracted * @param amount The amount to be extracted */ function extractTokenFee(address token, uint256 amount) external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("extractTokenFee(address,uint256)", token, amount) ); require(ok); } /** * @notice The function to get the balance from fee account. * @param token The token of the balance to be queried */ function getWalletBalance(address token) external returns (uint256 balance) { (bool ok, bytes memory ret) = _implementation().delegatecall( abi.encodeWithSignature("getWalletBalance(address)", token) ); require(ok); balance = abi.decode(ret, (uint256)); } /** * @notice The function to change the owner of fee wallet. * @param newOwner The new wallet owner to be assigned */ function changeWalletOwner(address newOwner) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("changeWalletOwner(address)", newOwner) ); require(ok); } /** * @notice The withdraw function that can only be triggered by owner. * Event Withdraw will be emitted after execution. * @param withdrawal The serialized withdrawal data */ function withdrawByAdmin(bytes calldata withdrawal, bytes calldata signature) external onlyAdmin { (bool ok, bytes memory ret) = _implementation().delegatecall( abi.encodeWithSignature("withdrawByAdmin(bytes,bytes)", withdrawal, signature) ); require(ok, string(ret)); } /** * @notice The transfer function that can only be triggered by owner. * Event Transfer will be emitted afer execution. * @param transferral The serialized transferral data. */ function transferByAdmin(bytes calldata transferral, bytes calldata signature) external onlyAdmin { (bool ok, bytes memory ret) = _implementation().delegatecall( abi.encodeWithSignature("transferByAdmin(bytes,bytes)", transferral, signature) ); require(ok, string(ret)); } /** * @notice The settle function for orders. First order is taker order and the followings * are maker orders. * @param orders The serialized orders. */ function settle(bytes calldata orders, bytes calldata signature) external onlyAdmin { (bool ok, bytes memory ret) = _implementation().delegatecall( abi.encodeWithSignature("settle(bytes,bytes)", orders, signature) ); require(ok, string(ret)); } /** * @notice The migrate function that can only be triggered by admin. * @param migration The serialized migration data */ function migrateByAdmin(bytes calldata migration, bytes calldata signature) external onlyAdmin { (bool ok, bytes memory ret) = _implementation().delegatecall( abi.encodeWithSignature("migrateByAdmin(bytes,bytes)", migration, signature) ); require(ok, string(ret)); } /** * @notice The migration handler * @param user The user address to receive the migrated amount. * @param token The token address to be migrated. * @param amount The amount to be migrated. */ function migrateTo(address user, address token, uint256 amount) payable external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("migrateTo(address,address,uint256)", user, token, amount) ); require(ok); } /** * @notice Announce lock of the sender */ function lock() external { (bool ok,) = _implementation().delegatecall(abi.encodeWithSignature("lock()")); require(ok); } /** * @notice Unlock the sender */ function unlock() external { (bool ok,) = _implementation().delegatecall(abi.encodeWithSignature("unlock()")); require(ok); } /** * @notice Change the processing time of locking the user address */ function changeProcessTime(uint256 time) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("changeProcessTime(uint256)", time) ); require(ok); } /** * @notice Get hash from the transferral parameters. */ function getTransferralHash( address from, uint8 config, uint32 nonce, address[] calldata tos, uint16[] calldata tokenIDs, uint256[] calldata amounts, uint256[] calldata fees ) external view returns (bytes32 hash) { (bool ok, bytes memory ret) = _implementation().staticcall( abi.encodeWithSignature( "getTransferralHash(address,uint8,uint32,address[],uint16[],uint256[],uint256[])", from, config, nonce, tos, tokenIDs, amounts, fees ) ); require(ok); hash = abi.decode(ret, (bytes32)); } }
* @notice The function to change the owner of fee wallet. @param newOwner The new wallet owner to be assigned/
function changeWalletOwner(address newOwner) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("changeWalletOwner(address)", newOwner) ); require(ok); }
14,016,253
[ 1, 1986, 445, 358, 2549, 326, 3410, 434, 14036, 9230, 18, 225, 394, 5541, 1021, 394, 9230, 3410, 358, 506, 6958, 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 ]
[ 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, 2549, 16936, 5541, 12, 2867, 394, 5541, 13, 3903, 1338, 5541, 288, 203, 3639, 261, 6430, 1529, 16, 13, 273, 389, 30810, 7675, 22216, 1991, 12, 203, 5411, 24126, 18, 3015, 1190, 5374, 2932, 3427, 16936, 5541, 12, 2867, 2225, 16, 394, 5541, 13, 203, 3639, 11272, 203, 3639, 2583, 12, 601, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; pragma experimental "v0.5.0"; /* Copyright 2018 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // File: openzeppelin-solidity/contracts/math/Math.sol /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a >= _b ? _a : _b; } function min64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a < _b ? _a : _b; } function max256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a >= _b ? _a : _b; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // File: openzeppelin-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 '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; } } // File: openzeppelin-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: contracts/lib/AccessControlledBase.sol /** * @title AccessControlledBase * @author dYdX * * Base functionality for access control. Requires an implementation to * provide a way to grant and optionally revoke access */ contract AccessControlledBase { // ============ State Variables ============ mapping (address => bool) public authorized; // ============ Events ============ event AccessGranted( address who ); event AccessRevoked( address who ); // ============ Modifiers ============ modifier requiresAuthorization() { require( authorized[msg.sender], "AccessControlledBase#requiresAuthorization: Sender not authorized" ); _; } } // File: contracts/lib/StaticAccessControlled.sol /** * @title StaticAccessControlled * @author dYdX * * Allows for functions to be access controled * Permissions cannot be changed after a grace period */ contract StaticAccessControlled is AccessControlledBase, Ownable { using SafeMath for uint256; // ============ State Variables ============ // Timestamp after which no additional access can be granted uint256 public GRACE_PERIOD_EXPIRATION; // ============ Constructor ============ constructor( uint256 gracePeriod ) public Ownable() { GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod); } // ============ Owner-Only State-Changing Functions ============ function grantAccess( address who ) external onlyOwner { require( block.timestamp < GRACE_PERIOD_EXPIRATION, "StaticAccessControlled#grantAccess: Cannot grant access after grace period" ); emit AccessGranted(who); authorized[who] = true; } } // File: contracts/lib/GeneralERC20.sol /** * @title GeneralERC20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we dont automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface GeneralERC20 { 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; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; } // File: contracts/lib/TokenInteract.sol /** * @title TokenInteract * @author dYdX * * This library contains functions for interacting with ERC20 tokens */ library TokenInteract { function balanceOf( address token, address owner ) internal view returns (uint256) { return GeneralERC20(token).balanceOf(owner); } function allowance( address token, address owner, address spender ) internal view returns (uint256) { return GeneralERC20(token).allowance(owner, spender); } function approve( address token, address spender, uint256 amount ) internal { GeneralERC20(token).approve(spender, amount); require( checkSuccess(), "TokenInteract#approve: Approval failed" ); } function transfer( address token, address to, uint256 amount ) internal { address from = address(this); if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transfer(to, amount); require( checkSuccess(), "TokenInteract#transfer: Transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transferFrom(from, to, amount); require( checkSuccess(), "TokenInteract#transferFrom: TransferFrom failed" ); } // ============ Private Helper-Functions ============ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. */ function checkSuccess( ) private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } return returnValue != 0; } } // File: contracts/margin/TokenProxy.sol /** * @title TokenProxy * @author dYdX * * Used to transfer tokens between addresses which have set allowance on this contract. */ contract TokenProxy is StaticAccessControlled { using SafeMath for uint256; // ============ Constructor ============ constructor( uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) {} // ============ Authorized-Only State Changing Functions ============ /** * Transfers tokens from an address (that has set allowance on the proxy) to another address. * * @param token The address of the ERC20 token * @param from The address to transfer token from * @param to The address to transfer tokens to * @param value The number of tokens to transfer */ function transferTokens( address token, address from, address to, uint256 value ) external requiresAuthorization { TokenInteract.transferFrom( token, from, to, value ); } // ============ Public Constant Functions ============ /** * Getter function to get the amount of token that the proxy is able to move for a particular * address. The minimum of 1) the balance of that address and 2) the allowance given to proxy. * * @param who The owner of the tokens * @param token The address of the ERC20 token * @return The number of tokens able to be moved by the proxy from the address specified */ function available( address who, address token ) external view returns (uint256) { return Math.min256( TokenInteract.allowance(token, who, address(this)), TokenInteract.balanceOf(token, who) ); } } // File: contracts/margin/Vault.sol /** * @title Vault * @author dYdX * * Holds and transfers tokens in vaults denominated by id * * Vault only supports ERC20 tokens, and will not accept any tokens that require * a tokenFallback or equivalent function (See ERC223, ERC777, etc.) */ contract Vault is StaticAccessControlled { using SafeMath for uint256; // ============ Events ============ event ExcessTokensWithdrawn( address indexed token, address indexed to, address caller ); // ============ State Variables ============ // Address of the TokenProxy contract. Used for moving tokens. address public TOKEN_PROXY; // Map from vault ID to map from token address to amount of that token attributed to the // particular vault ID. mapping (bytes32 => mapping (address => uint256)) public balances; // Map from token address to total amount of that token attributed to some account. mapping (address => uint256) public totalBalances; // ============ Constructor ============ constructor( address proxy, uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) { TOKEN_PROXY = proxy; } // ============ Owner-Only State-Changing Functions ============ /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY * will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { uint256 actualBalance = TokenInteract.balanceOf(token, address(this)); uint256 accountedBalance = totalBalances[token]; uint256 withdrawableBalance = actualBalance.sub(accountedBalance); require( withdrawableBalance != 0, "Vault#withdrawExcessToken: Withdrawable token amount must be non-zero" ); TokenInteract.transfer(token, to, withdrawableBalance); emit ExcessTokensWithdrawn(token, to, msg.sender); return withdrawableBalance; } // ============ Authorized-Only State-Changing Functions ============ /** * Transfers tokens from an address (that has approved the proxy) to the vault. * * @param id The vault which will receive the tokens * @param token ERC20 token address * @param from Address from which the tokens will be taken * @param amount Number of the token to be sent */ function transferToVault( bytes32 id, address token, address from, uint256 amount ) external requiresAuthorization { // First send tokens to this contract TokenProxy(TOKEN_PROXY).transferTokens( token, from, address(this), amount ); // Then increment balances balances[id][token] = balances[id][token].add(amount); totalBalances[token] = totalBalances[token].add(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); validateBalance(token); } /** * Transfers a certain amount of funds to an address. * * @param id The vault from which to send the tokens * @param token ERC20 token address * @param to Address to transfer tokens to * @param amount Number of the token to be sent */ function transferFromVault( bytes32 id, address token, address to, uint256 amount ) external requiresAuthorization { // Next line also asserts that (balances[id][token] >= amount); balances[id][token] = balances[id][token].sub(amount); // Next line also asserts that (totalBalances[token] >= amount); totalBalances[token] = totalBalances[token].sub(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); // Do the sending TokenInteract.transfer(token, to, amount); // asserts transfer succeeded // Final validation validateBalance(token); } // ============ Private Helper-Functions ============ /** * Verifies that this contract is in control of at least as many tokens as accounted for * * @param token Address of ERC20 token */ function validateBalance( address token ) private view { // The actual balance could be greater than totalBalances[token] because anyone // can send tokens to the contract's address which cannot be accounted for assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]); } } // File: contracts/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author dYdX * * Optimized version of the well-known ReentrancyGuard contract */ contract ReentrancyGuard { uint256 private _guardCounter = 1; modifier nonReentrant() { uint256 localCounter = _guardCounter + 1; _guardCounter = localCounter; _; require( _guardCounter == localCounter, "Reentrancy check failure" ); } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * 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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/lib/Fraction.sol /** * @title Fraction * @author dYdX * * This library contains implementations for fraction structs. */ library Fraction { struct Fraction128 { uint128 num; uint128 den; } } // File: contracts/lib/FractionMath.sol /** * @title FractionMath * @author dYdX * * This library contains safe math functions for manipulating fractions. */ library FractionMath { using SafeMath for uint256; using SafeMath for uint128; /** * Returns a Fraction128 that is equal to a + b * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (sum) */ function add( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { uint256 left = a.num.mul(b.den); uint256 right = b.num.mul(a.den); uint256 denominator = a.den.mul(b.den); // if left + right overflows, prevent overflow if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); } return bound(left.add(right), denominator); } /** * Returns a Fraction128 that is equal to a - (1/2)^d * * @param a The Fraction128 * @param d The power of (1/2) * @return The result */ function sub1Over( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.den % d == 0) { return bound( a.num.sub(a.den.div(d)), a.den ); } return bound( a.num.mul(d).sub(a.den), a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a / d * * @param a The first Fraction128 * @param d The divisor * @return The result (quotient) */ function div( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.num % d == 0) { return bound( a.num.div(d), a.den ); } return bound( a.num, a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a * b. * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (product) */ function mul( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { return bound( a.num.mul(b.num), a.den.mul(b.den) ); } /** * Returns a fraction from two uint256's. Fits them into uint128 if necessary. * * @param num The numerator * @param den The denominator * @return The Fraction128 that matches num/den most closely */ /* solium-disable-next-line security/no-assign-params */ function bound( uint256 num, uint256 den ) internal pure returns (Fraction.Fraction128 memory) { uint256 max = num > den ? num : den; uint256 first128Bits = (max >> 128); if (first128Bits != 0) { first128Bits += 1; num /= first128Bits; den /= first128Bits; } assert(den != 0); // coverage-enable-line assert(den < 2**128); assert(num < 2**128); return Fraction.Fraction128({ num: uint128(num), den: uint128(den) }); } /** * Returns an in-memory copy of a Fraction128 * * @param a The Fraction128 to copy * @return A copy of the Fraction128 */ function copy( Fraction.Fraction128 memory a ) internal pure returns (Fraction.Fraction128 memory) { validate(a); return Fraction.Fraction128({ num: a.num, den: a.den }); } // ============ Private Helper-Functions ============ /** * Asserts that a Fraction128 is valid (i.e. the denominator is non-zero) * * @param a The Fraction128 to validate */ function validate( Fraction.Fraction128 memory a ) private pure { assert(a.den != 0); // coverage-enable-line } } // File: contracts/lib/Exponent.sol /** * @title Exponent * @author dYdX * * This library contains an implementation for calculating e^X for arbitrary fraction X */ library Exponent { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ // 2**128 - 1 uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455; // Number of precomputed integers, X, for E^((1/2)^X) uint256 constant public MAX_PRECOMPUTE_PRECISION = 32; // Number of precomputed integers, X, for E^X uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32; // ============ Public Implementation Functions ============ /** * Returns e^X for any fraction X * * @param X The exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function exp( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { require( precomputePrecision <= MAX_PRECOMPUTE_PRECISION, "Exponent#exp: Precompute precision over maximum" ); Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } // get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2) uint256 integerX = uint256(Xcopy.num).div(Xcopy.den); // if X is less than 1, then just calculate X if (integerX == 0) { return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision); } // get e^integerX Fraction.Fraction128 memory expOfInt = getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS); while (integerX >= NUM_PRECOMPUTED_INTEGERS) { expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS)); integerX -= NUM_PRECOMPUTED_INTEGERS; } // multiply e^integerX by e^decimalX Fraction.Fraction128 memory decimalX = Fraction.Fraction128({ num: Xcopy.num % Xcopy.den, den: Xcopy.den }); return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt); } /** * Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then * Maclaurin Series approximation to reduce error. * * @param X Exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function expHybrid( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION); assert(X.num < X.den); // will also throw if precomputePrecision is larger than the array length in getDenominator Fraction.Fraction128 memory Xtemp = X.copy(); if (Xtemp.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); uint256 d = 1; // 2^i for (uint256 i = 1; i <= precomputePrecision; i++) { d *= 2; // if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d) if (d.mul(Xtemp.num) >= Xtemp.den) { Xtemp = Xtemp.sub1Over(uint128(d)); result = result.mul(getPrecomputedEToTheHalfToThe(i)); } } return result.mul(expMaclaurin(Xtemp, maclaurinPrecision)); } /** * Returns e^X for any X, using Maclaurin Series approximation * * e^X = SUM(X^n / n!) for n >= 0 * e^X = 1 + X/1! + X^2/2! + X^3/3! ... * * @param X Exponent * @param precision Accuracy of Maclaurin terms * @return e^X */ function expMaclaurin( Fraction.Fraction128 memory X, uint256 precision ) internal pure returns (Fraction.Fraction128 memory) { Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); Fraction.Fraction128 memory Xtemp = ONE(); for (uint256 i = 1; i <= precision; i++) { Xtemp = Xtemp.mul(Xcopy.div(uint128(i))); result = result.add(Xtemp); } return result; } /** * Returns a fraction roughly equaling E^((1/2)^x) for integer x */ function getPrecomputedEToTheHalfToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= MAX_PRECOMPUTE_PRECISION); uint128 denominator = [ 125182886983370532117250726298150828301, 206391688497133195273760705512282642279, 265012173823417992016237332255925138361, 300298134811882980317033350418940119802, 319665700530617779809390163992561606014, 329812979126047300897653247035862915816, 335006777809430963166468914297166288162, 337634268532609249517744113622081347950, 338955731696479810470146282672867036734, 339618401537809365075354109784799900812, 339950222128463181389559457827561204959, 340116253979683015278260491021941090650, 340199300311581465057079429423749235412, 340240831081268226777032180141478221816, 340261598367316729254995498374473399540, 340271982485676106947851156443492415142, 340277174663693808406010255284800906112, 340279770782412691177936847400746725466, 340281068849199706686796915841848278311, 340281717884450116236033378667952410919, 340282042402539547492367191008339680733, 340282204661700319870089970029119685699, 340282285791309720262481214385569134454, 340282326356121674011576912006427792656, 340282346638529464274601981200276914173, 340282356779733812753265346086924801364, 340282361850336100329388676752133324799, 340282364385637272451648746721404212564, 340282365653287865596328444437856608255, 340282366287113163939555716675618384724, 340282366604025813553891209601455838559, 340282366762482138471739420386372790954, 340282366841710300958333641874363209044 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } /** * Returns a fraction roughly equaling E^(x) for integer x */ function getPrecomputedEToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= NUM_PRECOMPUTED_INTEGERS); uint128 denominator = [ 340282366920938463463374607431768211455, 125182886983370532117250726298150828301, 46052210507670172419625860892627118820, 16941661466271327126146327822211253888, 6232488952727653950957829210887653621, 2292804553036637136093891217529878878, 843475657686456657683449904934172134, 310297353591408453462393329342695980, 114152017036184782947077973323212575, 41994180235864621538772677139808695, 15448795557622704876497742989562086, 5683294276510101335127414470015662, 2090767122455392675095471286328463, 769150240628514374138961856925097, 282954560699298259527814398449860, 104093165666968799599694528310221, 38293735615330848145349245349513, 14087478058534870382224480725096, 5182493555688763339001418388912, 1906532833141383353974257736699, 701374233231058797338605168652, 258021160973090761055471434334, 94920680509187392077350434438, 34919366901332874995585576427, 12846117181722897538509298435, 4725822410035083116489797150, 1738532907279185132707372378, 639570514388029575350057932, 235284843422800231081973821, 86556456714490055457751527, 31842340925906738090071268, 11714142585413118080082437, 4309392228124372433711936 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } // ============ Private Helper-Functions ============ function ONE() private pure returns (Fraction.Fraction128 memory) { return Fraction.Fraction128({ num: 1, den: 1 }); } } // File: contracts/lib/MathHelpers.sol /** * @title MathHelpers * @author dYdX * * This library helps with common math functions in Solidity */ library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } } // File: contracts/margin/impl/InterestImpl.sol /** * @title InterestImpl * @author dYdX * * A library that calculates continuously compounded interest for principal, time period, and * interest rate. */ library InterestImpl { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11; uint256 constant DEFAULT_MACLAURIN_PRECISION = 5; uint256 constant MAXIMUM_EXPONENT = 80; uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613; // ============ Public Implementation Functions ============ /** * Returns total tokens owed after accruing interest. Continuously compounding and accurate to * roughly 10^18 decimal places. Continuously compounding interest follows the formula: * I = P * e^(R*T) * * @param principal Principal of the interest calculation * @param interestRate Annual nominal interest percentage times 10**6. * (example: 5% = 5e6) * @param secondsOfInterest Number of seconds that interest has been accruing * @return Total amount of tokens owed. Greater than tokenAmount. */ function getCompoundedInterest( uint256 principal, uint256 interestRate, uint256 secondsOfInterest ) public pure returns (uint256) { uint256 numerator = interestRate.mul(secondsOfInterest); uint128 denominator = (10**8) * (365 * 1 days); // interestRate and secondsOfInterest should both be uint32 assert(numerator < 2**128); // fraction representing (Rate * Time) Fraction.Fraction128 memory rt = Fraction.Fraction128({ num: uint128(numerator), den: denominator }); // calculate e^(RT) Fraction.Fraction128 memory eToRT; if (numerator.div(denominator) >= MAXIMUM_EXPONENT) { // degenerate case: cap calculation eToRT = Fraction.Fraction128({ num: E_TO_MAXIUMUM_EXPONENT, den: 1 }); } else { // normal case: calculate e^(RT) eToRT = Exponent.exp( rt, DEFAULT_PRECOMPUTE_PRECISION, DEFAULT_MACLAURIN_PRECISION ); } // e^X for positive X should be greater-than or equal to 1 assert(eToRT.num >= eToRT.den); return safeMultiplyUint256ByFraction(principal, eToRT); } // ============ Private Helper-Functions ============ /** * Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator * and denominator of f are less than 2**128. */ function safeMultiplyUint256ByFraction( uint256 n, Fraction.Fraction128 memory f ) private pure returns (uint256) { uint256 term1 = n.div(2 ** 128); // first 128 bits uint256 term2 = n % (2 ** 128); // second 128 bits // uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f if (term1 > 0) { term1 = term1.mul(f.num); uint256 numBits = MathHelpers.getNumBits(term1); // reduce rounding error by shifting all the way to the left before dividing term1 = MathHelpers.divisionRoundedUp( term1 << (uint256(256).sub(numBits)), f.den); // continue shifting or reduce shifting to get the right number if (numBits > 128) { term1 = term1 << (numBits.sub(128)); } else if (numBits < 128) { term1 = term1 >> (uint256(128).sub(numBits)); } } // calculates term2 = term2 * f term2 = MathHelpers.getPartialAmountRoundedUp( f.num, f.den, term2 ); return term1.add(term2); } } // File: contracts/margin/impl/MarginState.sol /** * @title MarginState * @author dYdX * * Contains state for the Margin contract. Also used by libraries that implement Margin functions. */ library MarginState { struct State { // Address of the Vault contract address VAULT; // Address of the TokenProxy contract address TOKEN_PROXY; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been filled. mapping (bytes32 => uint256) loanFills; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been canceled. mapping (bytes32 => uint256) loanCancels; // Mapping from positionId -> Position, which stores all the open margin positions. mapping (bytes32 => MarginCommon.Position) positions; // Mapping from positionId -> bool, which stores whether the position has previously been // open, but is now closed. mapping (bytes32 => bool) closedPositions; // Mapping from positionId -> uint256, which stores the total amount of owedToken that has // ever been repaid to the lender for each position. Does not reset. mapping (bytes32 => uint256) totalOwedTokenRepaidToLender; } } // File: contracts/margin/interfaces/lender/LoanOwner.sol /** * @title LoanOwner * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a loan sell via the * transferLoan function or the atomic-assign to the "owner" field in a loan offering. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receiveLoanOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/PositionOwner.sol /** * @title PositionOwner * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PositionOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a position via the * transferPosition function or the atomic-assign to the "owner" field when opening a position. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receivePositionOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/TransferInternal.sol /** * @title TransferInternal * @author dYdX * * This library contains the implementation for transferring ownership of loans and positions. */ library TransferInternal { // ============ Events ============ /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a postion was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); // ============ Internal Implementation Functions ============ /** * Returns either the address of the new loan owner, or the address to which they wish to * pass ownership of the loan. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the loan * @param newOwner The intended owner of the loan * @return The address that the intended owner wishes to assign the loan to (may be * the same as the intended owner). */ function grantLoanOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit LoanTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantLoanOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantLoanOwnership: New owner did not consent to owning loan" ); return newOwner; } /** * Returns either the address of the new position owner, or the address to which they wish to * pass ownership of the position. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the position * @param newOwner The intended owner of the position * @return The address that the intended owner wishes to assign the position to (may * be the same as the intended owner). */ function grantPositionOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit PositionTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantPositionOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantPositionOwnership: New owner did not consent to owning position" ); return newOwner; } } // File: contracts/lib/TimestampHelper.sol /** * @title TimestampHelper * @author dYdX * * Helper to get block timestamps in other formats */ library TimestampHelper { function getBlockTimestamp32() internal view returns (uint32) { // Should not still be in-use in the year 2106 assert(uint256(uint32(block.timestamp)) == block.timestamp); assert(block.timestamp > 0); return uint32(block.timestamp); } } // File: contracts/margin/impl/MarginCommon.sol /** * @title MarginCommon * @author dYdX * * This library contains common functions for implementations of public facing Margin functions */ library MarginCommon { using SafeMath for uint256; // ============ Structs ============ struct Position { address owedToken; // Immutable address heldToken; // Immutable address lender; address owner; uint256 principal; uint256 requiredDeposit; uint32 callTimeLimit; // Immutable uint32 startTimestamp; // Immutable, cannot be 0 uint32 callTimestamp; uint32 maxDuration; // Immutable uint32 interestRate; // Immutable uint32 interestPeriod; // Immutable } struct LoanOffering { address owedToken; address heldToken; address payer; address owner; address taker; address positionOwner; address feeRecipient; address lenderFeeToken; address takerFeeToken; LoanRates rates; uint256 expirationTimestamp; uint32 callTimeLimit; uint32 maxDuration; uint256 salt; bytes32 loanHash; bytes signature; } struct LoanRates { uint256 maxAmount; uint256 minAmount; uint256 minHeldToken; uint256 lenderFee; uint256 takerFee; uint32 interestRate; uint32 interestPeriod; } // ============ Internal Implementation Functions ============ function storeNewPosition( MarginState.State storage state, bytes32 positionId, Position memory position, address loanPayer ) internal { assert(!positionHasExisted(state, positionId)); assert(position.owedToken != address(0)); assert(position.heldToken != address(0)); assert(position.owedToken != position.heldToken); assert(position.owner != address(0)); assert(position.lender != address(0)); assert(position.maxDuration != 0); assert(position.interestPeriod <= position.maxDuration); assert(position.callTimestamp == 0); assert(position.requiredDeposit == 0); state.positions[positionId].owedToken = position.owedToken; state.positions[positionId].heldToken = position.heldToken; state.positions[positionId].principal = position.principal; state.positions[positionId].callTimeLimit = position.callTimeLimit; state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32(); state.positions[positionId].maxDuration = position.maxDuration; state.positions[positionId].interestRate = position.interestRate; state.positions[positionId].interestPeriod = position.interestPeriod; state.positions[positionId].owner = TransferInternal.grantPositionOwnership( positionId, (position.owner != msg.sender) ? msg.sender : address(0), position.owner ); state.positions[positionId].lender = TransferInternal.grantLoanOwnership( positionId, (position.lender != loanPayer) ? loanPayer : address(0), position.lender ); } function getPositionIdFromNonce( uint256 nonce ) internal view returns (bytes32) { return keccak256(abi.encodePacked(msg.sender, nonce)); } function getUnavailableLoanOfferingAmountImpl( MarginState.State storage state, bytes32 loanHash ) internal view returns (uint256) { return state.loanFills[loanHash].add(state.loanCancels[loanHash]); } function cleanupPosition( MarginState.State storage state, bytes32 positionId ) internal { delete state.positions[positionId]; state.closedPositions[positionId] = true; } function calculateOwedAmount( Position storage position, uint256 closeAmount, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp); return InterestImpl.getCompoundedInterest( closeAmount, position.interestRate, timeElapsed ); } /** * Calculates time elapsed rounded up to the nearest interestPeriod */ function calculateEffectiveTimeElapsed( Position storage position, uint256 timestamp ) internal view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round up to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function calculateLenderAmountForIncreasePosition( Position storage position, uint256 principalToAdd, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp); return InterestImpl.getCompoundedInterest( principalToAdd, position.interestRate, timeElapsed ); } function getLoanOfferingHash( LoanOffering loanOffering ) internal view returns (bytes32) { return keccak256( abi.encodePacked( address(this), loanOffering.owedToken, loanOffering.heldToken, loanOffering.payer, loanOffering.owner, loanOffering.taker, loanOffering.positionOwner, loanOffering.feeRecipient, loanOffering.lenderFeeToken, loanOffering.takerFeeToken, getValuesHash(loanOffering) ) ); } function getPositionBalanceImpl( MarginState.State storage state, bytes32 positionId ) internal view returns(uint256) { return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken); } function containsPositionImpl( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return state.positions[positionId].startTimestamp != 0; } function positionHasExisted( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return containsPositionImpl(state, positionId) || state.closedPositions[positionId]; } function getPositionFromStorage( MarginState.State storage state, bytes32 positionId ) internal view returns (Position storage) { Position storage position = state.positions[positionId]; require( position.startTimestamp != 0, "MarginCommon#getPositionFromStorage: The position does not exist" ); return position; } // ============ Private Helper-Functions ============ /** * Calculates time elapsed rounded down to the nearest interestPeriod */ function calculateEffectiveTimeElapsedForNewLender( Position storage position, uint256 timestamp ) private view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round down to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = elapsed.div(period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function getValuesHash( LoanOffering loanOffering ) private pure returns (bytes32) { return keccak256( abi.encodePacked( loanOffering.rates.maxAmount, loanOffering.rates.minAmount, loanOffering.rates.minHeldToken, loanOffering.rates.lenderFee, loanOffering.rates.takerFee, loanOffering.expirationTimestamp, loanOffering.salt, loanOffering.callTimeLimit, loanOffering.maxDuration, loanOffering.rates.interestRate, loanOffering.rates.interestPeriod ) ); } } // File: contracts/margin/interfaces/PayoutRecipient.sol /** * @title PayoutRecipient * @author dYdX * * Interface that smart contracts must implement in order to be the payoutRecipient in a * closePosition transaction. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PayoutRecipient { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive payout from being the payoutRecipient * in a closePosition transaction. May redistribute any payout as necessary. Throws on error. * * @param positionId Unique ID of the position * @param closeAmount Amount of the position that was closed * @param closer Address of the account or contract that closed the position * @param positionOwner Address of the owner of the position * @param heldToken Address of the ERC20 heldToken * @param payout Number of tokens received from the payout * @param totalHeldToken Total amount of heldToken removed from vault during close * @param payoutInHeldToken True if payout is in heldToken, false if in owedToken * @return True if approved by the receiver */ function receiveClosePositionPayout( bytes32 positionId, uint256 closeAmount, address closer, address positionOwner, address heldToken, uint256 payout, uint256 totalHeldToken, bool payoutInHeldToken ) external /* onlyMargin */ returns (bool); } // File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol /** * @title CloseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CloseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * closeWithoutCounterparty(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at most) the specified amount of the loan was * successfully closed. * * @param closer Address of the caller of closeWithoutCounterparty() * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the loan to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeLoanOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol /** * @title ClosePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a position * owned by the smart contract, allowing more complex logic to control positions. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/impl/ClosePositionShared.sol /** * @title ClosePositionShared * @author dYdX * * This library contains shared functionality between ClosePositionImpl and * CloseWithoutCounterpartyImpl */ library ClosePositionShared { using SafeMath for uint256; // ============ Structs ============ struct CloseTx { bytes32 positionId; uint256 originalPrincipal; uint256 closeAmount; uint256 owedTokenOwed; uint256 startingHeldTokenBalance; uint256 availableHeldToken; address payoutRecipient; address owedToken; address heldToken; address positionOwner; address positionLender; address exchangeWrapper; bool payoutInHeldToken; } // ============ Internal Implementation Functions ============ function closePositionStateUpdate( MarginState.State storage state, CloseTx memory transaction ) internal { // Delete the position, or just decrease the principal if (transaction.closeAmount == transaction.originalPrincipal) { MarginCommon.cleanupPosition(state, transaction.positionId); } else { assert( transaction.originalPrincipal == state.positions[transaction.positionId].principal ); state.positions[transaction.positionId].principal = transaction.originalPrincipal.sub(transaction.closeAmount); } } function sendTokensToPayoutRecipient( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) internal returns (uint256) { uint256 payout; if (transaction.payoutInHeldToken) { // Send remaining heldToken to payoutRecipient payout = transaction.availableHeldToken.sub(buybackCostInHeldToken); Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.payoutRecipient, payout ); } else { assert(transaction.exchangeWrapper != address(0)); payout = receivedOwedToken.sub(transaction.owedTokenOwed); TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.payoutRecipient, payout ); } if (AddressUtils.isContract(transaction.payoutRecipient)) { require( PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout( transaction.positionId, transaction.closeAmount, msg.sender, transaction.positionOwner, transaction.heldToken, payout, transaction.availableHeldToken, transaction.payoutInHeldToken ), "ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent" ); } // The ending heldToken balance of the vault should be the starting heldToken balance // minus the available heldToken amount assert( MarginCommon.getPositionBalanceImpl(state, transaction.positionId) == transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken) ); return payout; } function createCloseTx( MarginState.State storage state, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) internal returns (CloseTx memory) { // Validate require( payoutRecipient != address(0), "ClosePositionShared#createCloseTx: Payout recipient cannot be 0" ); require( requestedAmount > 0, "ClosePositionShared#createCloseTx: Requested close amount cannot be 0" ); MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 closeAmount = getApprovedAmount( position, positionId, requestedAmount, payoutRecipient, isWithoutCounterparty ); return parseCloseTx( state, position, positionId, closeAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, isWithoutCounterparty ); } // ============ Private Helper-Functions ============ function getApprovedAmount( MarginCommon.Position storage position, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, bool requireLenderApproval ) private returns (uint256) { // Ensure enough principal uint256 allowedAmount = Math.min256(requestedAmount, position.principal); // Ensure owner consent allowedAmount = closePositionOnBehalfOfRecurse( position.owner, msg.sender, payoutRecipient, positionId, allowedAmount ); // Ensure lender consent if (requireLenderApproval) { allowedAmount = closeLoanOnBehalfOfRecurse( position.lender, msg.sender, payoutRecipient, positionId, allowedAmount ); } assert(allowedAmount > 0); assert(allowedAmount <= position.principal); assert(allowedAmount <= requestedAmount); return allowedAmount; } function closePositionOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = ClosePositionDelegator(contractAddr).closeOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closePositionRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closePositionOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } function closeLoanOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closeLoanRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closeLoanOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } // ============ Parsing Functions ============ function parseCloseTx( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 closeAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) private view returns (CloseTx memory) { uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); uint256 availableHeldToken = MathHelpers.getPartialAmount( closeAmount, position.principal, startingHeldTokenBalance ); uint256 owedTokenOwed = 0; if (!isWithoutCounterparty) { owedTokenOwed = MarginCommon.calculateOwedAmount( position, closeAmount, block.timestamp ); } return CloseTx({ positionId: positionId, originalPrincipal: position.principal, closeAmount: closeAmount, owedTokenOwed: owedTokenOwed, startingHeldTokenBalance: startingHeldTokenBalance, availableHeldToken: availableHeldToken, payoutRecipient: payoutRecipient, owedToken: position.owedToken, heldToken: position.heldToken, positionOwner: position.owner, positionLender: position.lender, exchangeWrapper: exchangeWrapper, payoutInHeldToken: payoutInHeldToken }); } } // File: contracts/margin/interfaces/ExchangeWrapper.sol /** * @title ExchangeWrapper * @author dYdX * * Contract interface that Exchange Wrapper smart contracts must implement in order to interface * with other smart contracts through a common interface. */ interface ExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the transaction */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes orderData ) external view returns (uint256); } // File: contracts/margin/impl/ClosePositionImpl.sol /** * @title ClosePositionImpl * @author dYdX * * This library contains the implementation for the closePosition function of Margin */ library ClosePositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData ) public returns (uint256, uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, false ); ( uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) = returnOwedTokensToLender( state, transaction, orderData ); uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, buybackCostInHeldToken, receivedOwedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnClose( transaction, buybackCostInHeldToken, payout ); return ( transaction.closeAmount, payout, transaction.owedTokenOwed ); } // ============ Private Helper-Functions ============ function returnOwedTokensToLender( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, bytes memory orderData ) private returns (uint256, uint256) { uint256 buybackCostInHeldToken = 0; uint256 receivedOwedToken = 0; uint256 lenderOwedToken = transaction.owedTokenOwed; // Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly // from msg.sender if (transaction.exchangeWrapper == address(0)) { require( transaction.payoutInHeldToken, "ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken" ); // No DEX Order; send owedTokens directly from the closer to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, msg.sender, transaction.positionLender, lenderOwedToken ); } else { // Buy back owedTokens using DEX Order and send to lender (buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken( state, transaction, orderData ); // If no owedToken needed for payout: give lender all owedToken, even if more than owed if (transaction.payoutInHeldToken) { assert(receivedOwedToken >= lenderOwedToken); lenderOwedToken = receivedOwedToken; } // Transfer owedToken from the exchange wrapper to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.positionLender, lenderOwedToken ); } state.totalOwedTokenRepaidToLender[transaction.positionId] = state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken); return (buybackCostInHeldToken, receivedOwedToken); } function buyBackOwedToken( MarginState.State storage state, ClosePositionShared.CloseTx transaction, bytes memory orderData ) private returns (uint256, uint256) { // Ask the exchange wrapper the cost in heldToken to buy back the close // amount of owedToken uint256 buybackCostInHeldToken; if (transaction.payoutInHeldToken) { buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper) .getExchangeCost( transaction.owedToken, transaction.heldToken, transaction.owedTokenOwed, orderData ); // Require enough available heldToken to pay for the buyback require( buybackCostInHeldToken <= transaction.availableHeldToken, "ClosePositionImpl#buyBackOwedToken: Not enough available heldToken" ); } else { buybackCostInHeldToken = transaction.availableHeldToken; } // Send the requisite heldToken to do the buyback from vault to exchange wrapper Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.exchangeWrapper, buybackCostInHeldToken ); // Trade the heldToken for the owedToken uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.owedToken, transaction.heldToken, buybackCostInHeldToken, orderData ); require( receivedOwedToken >= transaction.owedTokenOwed, "ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken" ); return (buybackCostInHeldToken, receivedOwedToken); } function logEventOnClose( ClosePositionShared.CloseTx transaction, uint256 buybackCostInHeldToken, uint256 payout ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), transaction.owedTokenOwed, payout, buybackCostInHeldToken, transaction.payoutInHeldToken ); } } // File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol /** * @title CloseWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the closeWithoutCounterpartyImpl function of * Margin */ library CloseWithoutCounterpartyImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closeWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) public returns (uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, true ); uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, 0, // No buyback cost 0 // Did not receive any owedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnCloseWithoutCounterparty(transaction); return ( transaction.closeAmount, heldTokenPayout ); } // ============ Private Helper-Functions ============ function logEventOnCloseWithoutCounterparty( ClosePositionShared.CloseTx transaction ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), 0, transaction.availableHeldToken, 0, true ); } } // File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol /** * @title DepositCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses deposit heldTokens * into a position owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface DepositCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call depositCollateral(). * * @param depositor Address of the caller of the depositCollateral() function * @param positionId Unique ID of the position * @param amount Requested deposit amount * @return This address to accept, a different address to ask that contract */ function depositCollateralOnBehalfOf( address depositor, bytes32 positionId, uint256 amount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/DepositCollateralImpl.sol /** * @title DepositCollateralImpl * @author dYdX * * This library contains the implementation for the deposit function of Margin */ library DepositCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); // ============ Public Implementation Functions ============ function depositCollateralImpl( MarginState.State storage state, bytes32 positionId, uint256 depositAmount ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( depositAmount > 0, "DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0" ); // Ensure owner consent depositCollateralOnBehalfOfRecurse( position.owner, msg.sender, positionId, depositAmount ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, depositAmount ); // cancel margin call if applicable bool marginCallCanceled = false; uint256 requiredDeposit = position.requiredDeposit; if (position.callTimestamp > 0 && requiredDeposit > 0) { if (depositAmount >= requiredDeposit) { position.requiredDeposit = 0; position.callTimestamp = 0; marginCallCanceled = true; } else { position.requiredDeposit = position.requiredDeposit.sub(depositAmount); } } emit AdditionalCollateralDeposited( positionId, depositAmount, msg.sender ); if (marginCallCanceled) { emit MarginCallCanceled( positionId, position.lender, msg.sender, depositAmount ); } } // ============ Private Helper-Functions ============ function depositCollateralOnBehalfOfRecurse( address contractAddr, address depositor, bytes32 positionId, uint256 amount ) private { // no need to ask for permission if (depositor == contractAddr) { return; } address newContractAddr = DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf( depositor, positionId, amount ); // if not equal, recurse if (newContractAddr != contractAddr) { depositCollateralOnBehalfOfRecurse( newContractAddr, depositor, positionId, amount ); } } } // File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol /** * @title ForceRecoverCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses * forceRecoverCollateral() a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ForceRecoverCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * NOTE: If not returning zero address (or not reverting), this contract must assume that Margin * will either revert the entire transaction or that the collateral was forcibly recovered. * * @param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address recoverer, bytes32 positionId, address recipient ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/ForceRecoverCollateralImpl.sol /** * @title ForceRecoverCollateralImpl * @author dYdX * * This library contains the implementation for the forceRecoverCollateral function of Margin */ library ForceRecoverCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); // ============ Public Implementation Functions ============ function forceRecoverCollateralImpl( MarginState.State storage state, bytes32 positionId, address recipient ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Can only force recover after either: // 1) The loan was called and the call period has elapsed // 2) The maxDuration of the position has elapsed require( /* solium-disable-next-line */ ( position.callTimestamp > 0 && block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit) ) || ( block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration) ), "ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet" ); // Ensure lender consent forceRecoverCollateralOnBehalfOfRecurse( position.lender, msg.sender, positionId, recipient ); // Send the tokens uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId); Vault(state.VAULT).transferFromVault( positionId, position.heldToken, recipient, heldTokenRecovered ); // Delete the position // NOTE: Since position is a storage pointer, this will also set all fields on // the position variable to 0 MarginCommon.cleanupPosition( state, positionId ); // Log an event emit CollateralForceRecovered( positionId, recipient, heldTokenRecovered ); return heldTokenRecovered; } // ============ Private Helper-Functions ============ function forceRecoverCollateralOnBehalfOfRecurse( address contractAddr, address recoverer, bytes32 positionId, address recipient ) private { // no need to ask for permission if (recoverer == contractAddr) { return; } address newContractAddr = ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf( recoverer, positionId, recipient ); if (newContractAddr != contractAddr) { forceRecoverCollateralOnBehalfOfRecurse( newContractAddr, recoverer, positionId, recipient ); } } } // File: contracts/lib/TypedSignature.sol /** * @title TypedSignature * @author dYdX * * Allows for ecrecovery of signed hashes with three different prepended messages: * 1) "" * 2) "\x19Ethereum Signed Message:\n32" * 3) "\x19Ethereum Signed Message:\n\x20" */ library TypedSignature { // Solidity does not offer guarantees about enum values, so we define them explicitly uint8 private constant SIGTYPE_INVALID = 0; uint8 private constant SIGTYPE_ECRECOVER_DEC = 1; uint8 private constant SIGTYPE_ECRECOVER_HEX = 2; uint8 private constant SIGTYPE_UNSUPPORTED = 3; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; /** * Gives the address of the signer of a hash. Allows for three common prepended strings. * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes signatureWithType ) internal pure returns (address) { require( signatureWithType.length == 66, "SignatureValidator#validateSignature: invalid signature length" ); uint8 sigType = uint8(signatureWithType[0]); require( sigType > uint8(SIGTYPE_INVALID), "SignatureValidator#validateSignature: invalid signature type" ); require( sigType < uint8(SIGTYPE_UNSUPPORTED), "SignatureValidator#validateSignature: unsupported signature type" ); uint8 v = uint8(signatureWithType[1]); bytes32 r; bytes32 s; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 34)) s := mload(add(signatureWithType, 66)) } bytes32 signedHash; if (sigType == SIGTYPE_ECRECOVER_DEC) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SIGTYPE_ECRECOVER_HEX); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } } // File: contracts/margin/interfaces/LoanOfferingVerifier.sol /** * @title LoanOfferingVerifier * @author dYdX * * Interface that smart contracts must implement to be able to make off-chain generated * loan offerings. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOfferingVerifier { /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * If true is returned, and no errors are thrown by the Margin contract, the loan will have * occurred. This means that verifyLoanOffering can also be used to update internal contract * state on a loan. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan positionOwner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param positionId Unique ID of the position * @param signature Arbitrary bytes; may or may not be an ECDSA signature * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/BorrowShared.sol /** * @title BorrowShared * @author dYdX * * This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl. * Both use a Loan Offering and a DEX Order to open or increase a position. */ library BorrowShared { using SafeMath for uint256; // ============ Structs ============ struct Tx { bytes32 positionId; address owner; uint256 principal; uint256 lenderAmount; MarginCommon.LoanOffering loanOffering; address exchangeWrapper; bool depositInHeldToken; uint256 depositAmount; uint256 collateralAmount; uint256 heldTokenFromSell; } // ============ Internal Implementation Functions ============ /** * Validate the transaction before exchanging heldToken for owedToken */ function validateTxPreSell( MarginState.State storage state, Tx memory transaction ) internal { assert(transaction.lenderAmount >= transaction.principal); require( transaction.principal > 0, "BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed" ); // If the taker is 0x0 then any address can take it. Otherwise only the taker can use it. if (transaction.loanOffering.taker != address(0)) { require( msg.sender == transaction.loanOffering.taker, "BorrowShared#validateTxPreSell: Invalid loan offering taker" ); } // If the positionOwner is 0x0 then any address can be set as the position owner. // Otherwise only the specified positionOwner can be set as the position owner. if (transaction.loanOffering.positionOwner != address(0)) { require( transaction.owner == transaction.loanOffering.positionOwner, "BorrowShared#validateTxPreSell: Invalid position owner" ); } // Require the loan offering to be approved by the payer if (AddressUtils.isContract(transaction.loanOffering.payer)) { getConsentFromSmartContractLender(transaction); } else { require( transaction.loanOffering.payer == TypedSignature.recover( transaction.loanOffering.loanHash, transaction.loanOffering.signature ), "BorrowShared#validateTxPreSell: Invalid loan offering signature" ); } // Validate the amount is <= than max and >= min uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl( state, transaction.loanOffering.loanHash ); require( transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount, "BorrowShared#validateTxPreSell: Loan offering does not have enough available" ); require( transaction.lenderAmount >= transaction.loanOffering.rates.minAmount, "BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount" ); require( transaction.loanOffering.owedToken != transaction.loanOffering.heldToken, "BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken" ); require( transaction.owner != address(0), "BorrowShared#validateTxPreSell: Position owner cannot be 0" ); require( transaction.loanOffering.owner != address(0), "BorrowShared#validateTxPreSell: Loan owner cannot be 0" ); require( transaction.loanOffering.expirationTimestamp > block.timestamp, "BorrowShared#validateTxPreSell: Loan offering is expired" ); require( transaction.loanOffering.maxDuration > 0, "BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration" ); require( transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration, "BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration" ); // The minimum heldToken is validated after executing the sell // Position and loan ownership is validated in TransferInternal } /** * Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store * how much of the loan was used. */ function doPostSell( MarginState.State storage state, Tx memory transaction ) internal { validateTxPostSell(transaction); // Transfer feeTokens from trader and lender transferLoanFees(state, transaction); // Update global amounts for the loan state.loanFills[transaction.loanOffering.loanHash] = state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount); } /** * Sells the owedToken from the lender (and from the deposit if in owedToken) using the * exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for * maxHeldTokenToBuy of heldTokens at most. */ function doSell( MarginState.State storage state, Tx transaction, bytes orderData, uint256 maxHeldTokenToBuy ) internal returns (uint256) { // Move owedTokens from lender to exchange wrapper pullOwedTokensFromLender(state, transaction); // Sell just the lender's owedToken (if trader deposit is in heldToken) // Otherwise sell both the lender's owedToken and the trader's deposit in owedToken uint256 sellAmount = transaction.depositInHeldToken ? transaction.lenderAmount : transaction.lenderAmount.add(transaction.depositAmount); // Do the trade, taking only the maxHeldTokenToBuy if more is returned uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData ) ); // Move the tokens to the vault Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, transaction.exchangeWrapper, heldTokenFromSell ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell); return heldTokenFromSell; } /** * Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can * be sold for heldToken. */ function doDepositOwedToken( MarginState.State storage state, Tx transaction ) internal { TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, msg.sender, transaction.exchangeWrapper, transaction.depositAmount ); } /** * Take the heldToken deposit from the trader and move it to the vault. */ function doDepositHeldToken( MarginState.State storage state, Tx transaction ) internal { Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, msg.sender, transaction.depositAmount ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount); } // ============ Private Helper-Functions ============ function validateTxPostSell( Tx transaction ) private pure { uint256 expectedCollateral = transaction.depositInHeldToken ? transaction.heldTokenFromSell.add(transaction.depositAmount) : transaction.heldTokenFromSell; assert(transaction.collateralAmount == expectedCollateral); uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minHeldToken ); require( transaction.collateralAmount >= loanOfferingMinimumHeldToken, "BorrowShared#validateTxPostSell: Loan offering minimum held token not met" ); } function getConsentFromSmartContractLender( Tx transaction ) private { verifyLoanOfferingRecurse( transaction.loanOffering.payer, getLoanOfferingAddresses(transaction), getLoanOfferingValues256(transaction), getLoanOfferingValues32(transaction), transaction.positionId, transaction.loanOffering.signature ); } function verifyLoanOfferingRecurse( address contractAddr, address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) private { address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering( addresses, values256, values32, positionId, signature ); if (newContractAddr != contractAddr) { verifyLoanOfferingRecurse( newContractAddr, addresses, values256, values32, positionId, signature ); } } function pullOwedTokensFromLender( MarginState.State storage state, Tx transaction ) private { // Transfer owedToken to the exchange wrapper TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, transaction.loanOffering.payer, transaction.exchangeWrapper, transaction.lenderAmount ); } function transferLoanFees( MarginState.State storage state, Tx transaction ) private { // 0 fee address indicates no fees if (transaction.loanOffering.feeRecipient == address(0)) { return; } TokenProxy proxy = TokenProxy(state.TOKEN_PROXY); uint256 lenderFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.lenderFee ); uint256 takerFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.takerFee ); if (lenderFee > 0) { proxy.transferTokens( transaction.loanOffering.lenderFeeToken, transaction.loanOffering.payer, transaction.loanOffering.feeRecipient, lenderFee ); } if (takerFee > 0) { proxy.transferTokens( transaction.loanOffering.takerFeeToken, msg.sender, transaction.loanOffering.feeRecipient, takerFee ); } } function getLoanOfferingAddresses( Tx transaction ) private pure returns (address[9]) { return [ transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.payer, transaction.loanOffering.owner, transaction.loanOffering.taker, transaction.loanOffering.positionOwner, transaction.loanOffering.feeRecipient, transaction.loanOffering.lenderFeeToken, transaction.loanOffering.takerFeeToken ]; } function getLoanOfferingValues256( Tx transaction ) private pure returns (uint256[7]) { return [ transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minAmount, transaction.loanOffering.rates.minHeldToken, transaction.loanOffering.rates.lenderFee, transaction.loanOffering.rates.takerFee, transaction.loanOffering.expirationTimestamp, transaction.loanOffering.salt ]; } function getLoanOfferingValues32( Tx transaction ) private pure returns (uint32[4]) { return [ transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.loanOffering.rates.interestRate, transaction.loanOffering.rates.interestPeriod ]; } } // File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol /** * @title IncreaseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreaseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned loan. Margin will call this on the owner of a loan during increasePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan size was successfully increased. * * @param payer Lender adding additional funds to the position * @param positionId Unique ID of the position * @param principalAdded Principal amount to be added to the position * @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or * zero if increaseWithoutCounterparty() is used). * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol /** * @title IncreasePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreasePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned position. Margin will call this on the owner of a position during increasePosition() * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the position size was successfully increased. * * @param trader Address initiating the addition of funds to the position * @param positionId Unique ID of the position * @param principalAdded Amount of principal to be added to the position * @return This address to accept, a different address to ask that contract */ function increasePositionOnBehalfOf( address trader, bytes32 positionId, uint256 principalAdded ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/IncreasePositionImpl.sol /** * @title IncreasePositionImpl * @author dYdX * * This library contains the implementation for the increasePosition function of Margin */ library IncreasePositionImpl { using SafeMath for uint256; // ============ Events ============ /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function increasePositionImpl( MarginState.State storage state, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (uint256) { // Also ensures that the position exists MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); BorrowShared.Tx memory transaction = parseIncreasePositionTx( position, positionId, addresses, values256, values32, depositInHeldToken, signature ); validateIncrease(state, transaction, position); doBorrowAndSell(state, transaction, orderData); updateState( position, transaction.positionId, transaction.principal, transaction.lenderAmount, transaction.loanOffering.payer ); // LOG EVENT recordPositionIncreased(transaction, position); return transaction.lenderAmount; } function increaseWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 principalToAdd ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Disallow adding 0 principal require( principalToAdd > 0, "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal" ); // Disallow additions after maximum duration require( block.timestamp < uint256(position.startTimestamp).add(position.maxDuration), "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration" ); uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal( state, position, positionId, principalToAdd ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, heldTokenAmount ); updateState( position, positionId, principalToAdd, 0, // lent amount msg.sender ); emit PositionIncreased( positionId, msg.sender, msg.sender, position.owner, position.lender, "", address(0), 0, principalToAdd, 0, heldTokenAmount, true ); return heldTokenAmount; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { // Calculate the number of heldTokens to add uint256 collateralToAdd = getCollateralNeededForAddedPrincipal( state, state.positions[transaction.positionId], transaction.positionId, transaction.principal ); // Do pre-exchange validations BorrowShared.validateTxPreSell(state, transaction); // Calculate and deposit owedToken uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; } // Sell owedToken for heldToken using the exchange wrapper transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, maxHeldTokenFromSell ); // Calculate and deposit heldToken if (transaction.depositInHeldToken) { require( transaction.heldTokenFromSell <= collateralToAdd, "IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken" ); transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell); BorrowShared.doDepositHeldToken(state, transaction); } // Make sure the actual added collateral is what is expected assert(transaction.collateralAmount == collateralToAdd); // Do post-exchange validations BorrowShared.doPostSell(state, transaction); } function getOwedTokenDeposit( BorrowShared.Tx transaction, uint256 collateralToAdd, bytes orderData ) private view returns (uint256) { uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost( transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, collateralToAdd, orderData ); require( transaction.lenderAmount <= totalOwedToken, "IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required" ); return totalOwedToken.sub(transaction.lenderAmount); } function validateIncrease( MarginState.State storage state, BorrowShared.Tx transaction, MarginCommon.Position storage position ) private view { assert(MarginCommon.containsPositionImpl(state, transaction.positionId)); require( position.callTimeLimit <= transaction.loanOffering.callTimeLimit, "IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position" ); // require the position to end no later than the loanOffering's maximum acceptable end time uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration); uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration); require( positionEndTimestamp <= offeringEndTimestamp, "IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position" ); require( block.timestamp < positionEndTimestamp, "IncreasePositionImpl#validateIncrease: Position has passed its maximum duration" ); } function getCollateralNeededForAddedPrincipal( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 principalToAdd ) private view returns (uint256) { uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); return MathHelpers.getPartialAmountRoundedUp( principalToAdd, position.principal, heldTokenBalance ); } function updateState( MarginCommon.Position storage position, bytes32 positionId, uint256 principalAdded, uint256 owedTokenLent, address loanPayer ) private { position.principal = position.principal.add(principalAdded); address owner = position.owner; address lender = position.lender; // Ensure owner consent increasePositionOnBehalfOfRecurse( owner, msg.sender, positionId, principalAdded ); // Ensure lender consent increaseLoanOnBehalfOfRecurse( lender, loanPayer, positionId, principalAdded, owedTokenLent ); } function increasePositionOnBehalfOfRecurse( address contractAddr, address trader, bytes32 positionId, uint256 principalAdded ) private { // Assume owner approval if not a smart contract and they increased their own position if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf( trader, positionId, principalAdded ); if (newContractAddr != contractAddr) { increasePositionOnBehalfOfRecurse( newContractAddr, trader, positionId, principalAdded ); } } function increaseLoanOnBehalfOfRecurse( address contractAddr, address payer, bytes32 positionId, uint256 principalAdded, uint256 amountLent ) private { // Assume lender approval if not a smart contract and they increased their own loan if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf( payer, positionId, principalAdded, amountLent ); if (newContractAddr != contractAddr) { increaseLoanOnBehalfOfRecurse( newContractAddr, payer, positionId, principalAdded, amountLent ); } } function recordPositionIncreased( BorrowShared.Tx transaction, MarginCommon.Position storage position ) private { emit PositionIncreased( transaction.positionId, msg.sender, transaction.loanOffering.payer, position.owner, position.lender, transaction.loanOffering.loanHash, transaction.loanOffering.feeRecipient, transaction.lenderAmount, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseIncreasePositionTx( MarginCommon.Position storage position, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { uint256 principal = values256[7]; uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition( position, principal, block.timestamp ); assert(lenderAmount >= principal); BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: positionId, owner: position.owner, principal: principal, lenderAmount: lenderAmount, loanOffering: parseLoanOfferingFromIncreasePositionTx( position, addresses, values256, values32, signature ), exchangeWrapper: addresses[6], depositInHeldToken: depositInHeldToken, depositAmount: 0, // set later collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOfferingFromIncreasePositionTx( MarginCommon.Position storage position, address[7] addresses, uint256[8] values256, uint32[2] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: position.owedToken, heldToken: position.heldToken, payer: addresses[0], owner: position.lender, taker: addresses[1], positionOwner: addresses[2], feeRecipient: addresses[3], lenderFeeToken: addresses[4], takerFeeToken: addresses[5], rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferingRatesFromIncreasePositionTx( MarginCommon.Position storage position, uint256[8] values256 ) private view returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: position.interestRate, interestPeriod: position.interestPeriod }); return rates; } } // File: contracts/margin/impl/MarginStorage.sol /** * @title MarginStorage * @author dYdX * * This contract serves as the storage for the entire state of MarginStorage */ contract MarginStorage { MarginState.State state; } // File: contracts/margin/impl/LoanGetters.sol /** * @title LoanGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any loan * offering stored in the dYdX protocol. */ contract LoanGetters is MarginStorage { // ============ Public Constant Functions ============ /** * Gets the principal amount of a loan offering that is no longer available. * * @param loanHash Unique hash of the loan offering * @return The total unavailable amount of the loan offering, which is equal to the * filled amount plus the canceled amount. */ function getLoanUnavailableAmount( bytes32 loanHash ) external view returns (uint256) { return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash); } /** * Gets the total amount of owed token lent for a loan. * * @param loanHash Unique hash of the loan offering * @return The total filled amount of the loan offering. */ function getLoanFilledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanFills[loanHash]; } /** * Gets the amount of a loan offering that has been canceled. * * @param loanHash Unique hash of the loan offering * @return The total canceled amount of the loan offering. */ function getLoanCanceledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanCancels[loanHash]; } } // File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol /** * @title CancelMarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses cancel a * margin-call for a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CancelMarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the margin-call was successfully canceled. * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/lender/MarginCallDelegator.sol /** * @title MarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses margin-call a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface MarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call marginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan was successfully margin-called. * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/LoanImpl.sol /** * @title LoanImpl * @author dYdX * * This library contains the implementation for the following functions of Margin: * * - marginCall * - cancelMarginCallImpl * - cancelLoanOffering */ library LoanImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); // ============ Public Implementation Functions ============ function marginCallImpl( MarginState.State storage state, bytes32 positionId, uint256 requiredDeposit ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp == 0, "LoanImpl#marginCallImpl: The position has already been margin-called" ); // Ensure lender consent marginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId, requiredDeposit ); position.callTimestamp = TimestampHelper.getBlockTimestamp32(); position.requiredDeposit = requiredDeposit; emit MarginCallInitiated( positionId, position.lender, position.owner, requiredDeposit ); } function cancelMarginCallImpl( MarginState.State storage state, bytes32 positionId ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp > 0, "LoanImpl#cancelMarginCallImpl: Position has not been margin-called" ); // Ensure lender consent cancelMarginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId ); state.positions[positionId].callTimestamp = 0; state.positions[positionId].requiredDeposit = 0; emit MarginCallCanceled( positionId, position.lender, position.owner, 0 ); } function cancelLoanOfferingImpl( MarginState.State storage state, address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) public returns (uint256) { MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32 ); require( msg.sender == loanOffering.payer, "LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel" ); require( loanOffering.expirationTimestamp > block.timestamp, "LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired" ); uint256 remainingAmount = loanOffering.rates.maxAmount.sub( MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash) ); uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount); // If the loan was already fully canceled, then just return 0 amount was canceled if (amountToCancel == 0) { return 0; } state.loanCancels[loanOffering.loanHash] = state.loanCancels[loanOffering.loanHash].add(amountToCancel); emit LoanOfferingCanceled( loanOffering.loanHash, loanOffering.payer, loanOffering.feeRecipient, amountToCancel ); return amountToCancel; } // ============ Private Helper-Functions ============ function marginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId, uint256 requiredDeposit ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = MarginCallDelegator(contractAddr).marginCallOnBehalfOf( msg.sender, positionId, requiredDeposit ); if (newContractAddr != contractAddr) { marginCallOnBehalfOfRecurse( newContractAddr, who, positionId, requiredDeposit ); } } function cancelMarginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf( msg.sender, positionId ); if (newContractAddr != contractAddr) { cancelMarginCallOnBehalfOfRecurse( newContractAddr, who, positionId ); } } // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32 ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[0], heldToken: addresses[1], payer: addresses[2], owner: addresses[3], taker: addresses[4], positionOwner: addresses[5], feeRecipient: addresses[6], lenderFeeToken: addresses[7], takerFeeToken: addresses[8], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: new bytes(0) }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[7] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], interestRate: values32[2], lenderFee: values256[3], takerFee: values256[4], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/MarginAdmin.sol /** * @title MarginAdmin * @author dYdX * * Contains admin functions for the Margin contract * The owner can put Margin into various close-only modes, which will disallow new position creation */ contract MarginAdmin is Ownable { // ============ Enums ============ // All functionality enabled uint8 private constant OPERATION_STATE_OPERATIONAL = 0; // Only closing functions + cancelLoanOffering allowed (marginCall, closePosition, // cancelLoanOffering, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1; // Only closing functions allowed (marginCall, closePosition, closePositionDirectly, // forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2; // Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3; // This operation state (and any higher) is invalid uint8 private constant OPERATION_STATE_INVALID = 4; // ============ Events ============ /** * Event indicating the operation state has changed */ event OperationStateChanged( uint8 from, uint8 to ); // ============ State Variables ============ uint8 public operationState; // ============ Constructor ============ constructor() public Ownable() { operationState = OPERATION_STATE_OPERATIONAL; } // ============ Modifiers ============ modifier onlyWhileOperational() { require( operationState == OPERATION_STATE_OPERATIONAL, "MarginAdmin#onlyWhileOperational: Can only call while operational" ); _; } modifier cancelLoanOfferingStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY, "MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state" ); _; } modifier closePositionStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY || operationState == OPERATION_STATE_CLOSE_ONLY, "MarginAdmin#closePositionStateControl: Invalid operation state" ); _; } modifier closePositionDirectlyStateControl() { _; } // ============ Owner-Only State-Changing Functions ============ function setOperationState( uint8 newState ) external onlyOwner { require( newState < OPERATION_STATE_INVALID, "MarginAdmin#setOperationState: newState is not a valid operation state" ); if (newState != operationState) { emit OperationStateChanged( operationState, newState ); operationState = newState; } } } // File: contracts/margin/impl/MarginEvents.sol /** * @title MarginEvents * @author dYdX * * Contains events for the Margin contract. * * NOTE: Any Margin function libraries that use events will need to both define the event here * and copy the event into the library itself as libraries don't support sharing events */ contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); } // File: contracts/margin/impl/OpenPositionImpl.sol /** * @title OpenPositionImpl * @author dYdX * * This library contains the implementation for the openPosition function of Margin */ library OpenPositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openPositionImpl( MarginState.State storage state, address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (bytes32) { BorrowShared.Tx memory transaction = parseOpenTx( addresses, values256, values32, depositInHeldToken, signature ); require( !MarginCommon.positionHasExisted(state, transaction.positionId), "OpenPositionImpl#openPositionImpl: positionId already exists" ); doBorrowAndSell(state, transaction, orderData); // Before doStoreNewPosition() so that PositionOpened event is before Transferred events recordPositionOpened( transaction ); doStoreNewPosition( state, transaction ); return transaction.positionId; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { BorrowShared.validateTxPreSell(state, transaction); if (transaction.depositInHeldToken) { BorrowShared.doDepositHeldToken(state, transaction); } else { BorrowShared.doDepositOwedToken(state, transaction); } transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, MathHelpers.maxUint256() ); BorrowShared.doPostSell(state, transaction); } function doStoreNewPosition( MarginState.State storage state, BorrowShared.Tx memory transaction ) private { MarginCommon.storeNewPosition( state, transaction.positionId, MarginCommon.Position({ owedToken: transaction.loanOffering.owedToken, heldToken: transaction.loanOffering.heldToken, lender: transaction.loanOffering.owner, owner: transaction.owner, principal: transaction.principal, requiredDeposit: 0, callTimeLimit: transaction.loanOffering.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: transaction.loanOffering.maxDuration, interestRate: transaction.loanOffering.rates.interestRate, interestPeriod: transaction.loanOffering.rates.interestPeriod }), transaction.loanOffering.payer ); } function recordPositionOpened( BorrowShared.Tx transaction ) private { emit PositionOpened( transaction.positionId, msg.sender, transaction.loanOffering.payer, transaction.loanOffering.loanHash, transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.feeRecipient, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.loanOffering.rates.interestRate, transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseOpenTx( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[9]), owner: addresses[0], principal: values256[7], lenderAmount: values256[7], loanOffering: parseLoanOffering( addresses, values256, values32, signature ), exchangeWrapper: addresses[10], depositInHeldToken: depositInHeldToken, depositAmount: values256[8], collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOffering( address[11] addresses, uint256[10] values256, uint32[4] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[1], heldToken: addresses[2], payer: addresses[3], owner: addresses[4], taker: addresses[5], positionOwner: addresses[6], feeRecipient: addresses[7], lenderFeeToken: addresses[8], takerFeeToken: addresses[9], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[10] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: values32[2], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol /** * @title OpenWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the openWithoutCounterparty * function of Margin */ library OpenWithoutCounterpartyImpl { // ============ Structs ============ struct Tx { bytes32 positionId; address positionOwner; address owedToken; address heldToken; address loanOwner; uint256 principal; uint256 deposit; uint32 callTimeLimit; uint32 maxDuration; uint32 interestRate; uint32 interestPeriod; } // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openWithoutCounterpartyImpl( MarginState.State storage state, address[4] addresses, uint256[3] values256, uint32[4] values32 ) public returns (bytes32) { Tx memory openTx = parseTx( addresses, values256, values32 ); validate( state, openTx ); Vault(state.VAULT).transferToVault( openTx.positionId, openTx.heldToken, msg.sender, openTx.deposit ); recordPositionOpened( openTx ); doStoreNewPosition( state, openTx ); return openTx.positionId; } // ============ Private Helper-Functions ============ function doStoreNewPosition( MarginState.State storage state, Tx memory openTx ) private { MarginCommon.storeNewPosition( state, openTx.positionId, MarginCommon.Position({ owedToken: openTx.owedToken, heldToken: openTx.heldToken, lender: openTx.loanOwner, owner: openTx.positionOwner, principal: openTx.principal, requiredDeposit: 0, callTimeLimit: openTx.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: openTx.maxDuration, interestRate: openTx.interestRate, interestPeriod: openTx.interestPeriod }), msg.sender ); } function validate( MarginState.State storage state, Tx memory openTx ) private view { require( !MarginCommon.positionHasExisted(state, openTx.positionId), "openWithoutCounterpartyImpl#validate: positionId already exists" ); require( openTx.principal > 0, "openWithoutCounterpartyImpl#validate: principal cannot be 0" ); require( openTx.owedToken != address(0), "openWithoutCounterpartyImpl#validate: owedToken cannot be 0" ); require( openTx.owedToken != openTx.heldToken, "openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken" ); require( openTx.positionOwner != address(0), "openWithoutCounterpartyImpl#validate: positionOwner cannot be 0" ); require( openTx.loanOwner != address(0), "openWithoutCounterpartyImpl#validate: loanOwner cannot be 0" ); require( openTx.maxDuration > 0, "openWithoutCounterpartyImpl#validate: maxDuration cannot be 0" ); require( openTx.interestPeriod <= openTx.maxDuration, "openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration" ); } function recordPositionOpened( Tx memory openTx ) private { emit PositionOpened( openTx.positionId, msg.sender, msg.sender, bytes32(0), openTx.owedToken, openTx.heldToken, address(0), openTx.principal, 0, openTx.deposit, openTx.interestRate, openTx.callTimeLimit, openTx.maxDuration, true ); } // ============ Parsing Functions ============ function parseTx( address[4] addresses, uint256[3] values256, uint32[4] values32 ) private view returns (Tx memory) { Tx memory openTx = Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[2]), positionOwner: addresses[0], owedToken: addresses[1], heldToken: addresses[2], loanOwner: addresses[3], principal: values256[0], deposit: values256[1], callTimeLimit: values32[0], maxDuration: values32[1], interestRate: values32[2], interestPeriod: values32[3] }); return openTx; } } // File: contracts/margin/impl/PositionGetters.sol /** * @title PositionGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any position * stored in the dYdX protocol. */ contract PositionGetters is MarginStorage { using SafeMath for uint256; // ============ Public Constant Functions ============ /** * Gets if a position is currently open. * * @param positionId Unique ID of the position * @return True if the position is exists and is open */ function containsPosition( bytes32 positionId ) external view returns (bool) { return MarginCommon.containsPositionImpl(state, positionId); } /** * Gets if a position is currently margin-called. * * @param positionId Unique ID of the position * @return True if the position is margin-called */ function isPositionCalled( bytes32 positionId ) external view returns (bool) { return (state.positions[positionId].callTimestamp > 0); } /** * Gets if a position was previously open and is now closed. * * @param positionId Unique ID of the position * @return True if the position is now closed */ function isPositionClosed( bytes32 positionId ) external view returns (bool) { return state.closedPositions[positionId]; } /** * Gets the total amount of owedToken ever repaid to the lender for a position. * * @param positionId Unique ID of the position * @return Total amount of owedToken ever repaid */ function getTotalOwedTokenRepaidToLender( bytes32 positionId ) external view returns (uint256) { return state.totalOwedTokenRepaidToLender[positionId]; } /** * Gets the amount of heldToken currently locked up in Vault for a particular position. * * @param positionId Unique ID of the position * @return The amount of heldToken */ function getPositionBalance( bytes32 positionId ) external view returns (uint256) { return MarginCommon.getPositionBalanceImpl(state, positionId); } /** * Gets the time until the interest fee charged for the position will increase. * Returns 1 if the interest fee increases every second. * Returns 0 if the interest fee will never increase again. * * @param positionId Unique ID of the position * @return The number of seconds until the interest fee will increase */ function getTimeUntilInterestIncrease( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed( position, block.timestamp ); uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp); if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration return 0; } else { // nextStep is the final second at which the calculated interest fee is the same as it // is currently, so add 1 to get the correct value return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed); } } /** * Gets the amount of owedTokens currently needed to close the position completely, including * interest fees. * * @param positionId Unique ID of the position * @return The number of owedTokens */ function getPositionOwedAmount( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); return MarginCommon.calculateOwedAmount( position, position.principal, block.timestamp ); } /** * Gets the amount of owedTokens needed to close a given principal amount of the position at a * given time, including interest fees. * * @param positionId Unique ID of the position * @param principalToClose Amount of principal being closed * @param timestamp Block timestamp in seconds of close * @return The number of owedTokens owed */ function getPositionOwedAmountAtTime( bytes32 positionId, uint256 principalToClose, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getPositionOwedAmountAtTime: Requested time before position started" ); return MarginCommon.calculateOwedAmount( position, principalToClose, timestamp ); } /** * Gets the amount of owedTokens that can be borrowed from a lender to add a given principal * amount to the position at a given time. * * @param positionId Unique ID of the position * @param principalToAdd Amount being added to principal * @param timestamp Block timestamp in seconds of addition * @return The number of owedTokens that will be borrowed */ function getLenderAmountForIncreasePositionAtTime( bytes32 positionId, uint256 principalToAdd, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start" ); return MarginCommon.calculateLenderAmountForIncreasePosition( position, principalToAdd, timestamp ); } // ============ All Properties ============ /** * Get a Position by id. This does not validate the position exists. If the position does not * exist, all 0's will be returned. * * @param positionId Unique ID of the position * @return Addresses corresponding to: * * [0] = owedToken * [1] = heldToken * [2] = lender * [3] = owner * * Values corresponding to: * * [0] = principal * [1] = requiredDeposit * * Values corresponding to: * * [0] = callTimeLimit * [1] = startTimestamp * [2] = callTimestamp * [3] = maxDuration * [4] = interestRate * [5] = interestPeriod */ function getPosition( bytes32 positionId ) external view returns ( address[4], uint256[2], uint32[6] ) { MarginCommon.Position storage position = state.positions[positionId]; return ( [ position.owedToken, position.heldToken, position.lender, position.owner ], [ position.principal, position.requiredDeposit ], [ position.callTimeLimit, position.startTimestamp, position.callTimestamp, position.maxDuration, position.interestRate, position.interestPeriod ] ); } // ============ Individual Properties ============ function getPositionLender( bytes32 positionId ) external view returns (address) { return state.positions[positionId].lender; } function getPositionOwner( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owner; } function getPositionHeldToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].heldToken; } function getPositionOwedToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owedToken; } function getPositionPrincipal( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].principal; } function getPositionInterestRate( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].interestRate; } function getPositionRequiredDeposit( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].requiredDeposit; } function getPositionStartTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].startTimestamp; } function getPositionCallTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimestamp; } function getPositionCallTimeLimit( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimeLimit; } function getPositionMaxDuration( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].maxDuration; } function getPositioninterestPeriod( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].interestPeriod; } } // File: contracts/margin/impl/TransferImpl.sol /** * @title TransferImpl * @author dYdX * * This library contains the implementation for the transferPosition and transferLoan functions of * Margin */ library TransferImpl { // ============ Public Implementation Functions ============ function transferLoanImpl( MarginState.State storage state, bytes32 positionId, address newLender ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferLoanImpl: Position does not exist" ); address originalLender = state.positions[positionId].lender; require( msg.sender == originalLender, "TransferImpl#transferLoanImpl: Only lender can transfer ownership" ); require( newLender != originalLender, "TransferImpl#transferLoanImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of loan. // That is, newLender may pass ownership to a different address. address finalLender = TransferInternal.grantLoanOwnership( positionId, originalLender, newLender); require( finalLender != originalLender, "TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].lender = finalLender; } function transferPositionImpl( MarginState.State storage state, bytes32 positionId, address newOwner ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferPositionImpl: Position does not exist" ); address originalOwner = state.positions[positionId].owner; require( msg.sender == originalOwner, "TransferImpl#transferPositionImpl: Only position owner can transfer ownership" ); require( newOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of position. // That is, newOwner may pass ownership to a different address. address finalOwner = TransferInternal.grantPositionOwnership( positionId, originalOwner, newOwner); require( finalOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].owner = finalOwner; } } // File: contracts/margin/Margin.sol /** * @title Margin * @author dYdX * * This contract is used to facilitate margin trading as per the dYdX protocol */ contract Margin is ReentrancyGuard, MarginStorage, MarginEvents, MarginAdmin, LoanGetters, PositionGetters { using SafeMath for uint256; // ============ Constructor ============ constructor( address vault, address proxy ) public MarginAdmin() { state = MarginState.State({ VAULT: vault, TOKEN_PROXY: proxy }); } // ============ Public State Changing Functions ============ /** * Open a margin position. Called by the margin trader who must provide both a * signed loan offering as well as a DEX Order with which to sell the owedToken. * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan payer * [4] = loan owner * [5] = loan taker * [6] = loan position owner * [7] = loan fee recipient * [8] = loan lender fee token * [9] = loan taker fee token * [10] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = position amount of principal * [8] = deposit amount * [9] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Unique ID for the new position */ function openPosition( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenPositionImpl.openPositionImpl( state, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Open a margin position without a counterparty. The caller will serve as both the * lender and the position owner * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan owner * * @param values256 Values corresponding to: * * [0] = principal * [1] = deposit amount * [2] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = call time limit (in seconds) * [1] = maxDuration (in seconds) * [2] = interest rate (annual nominal percentage times 10**6) * [3] = interest update period (in seconds) * * @return Unique ID for the new position */ function openWithoutCounterparty( address[4] addresses, uint256[3] values256, uint32[4] values32 ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl( state, addresses, values256, values32 ); } /** * Increase the size of a position. Funds will be borrowed from the loan payer and sold as per * the position. The amount of owedToken borrowed from the lender will be >= the amount of * principal added, as it will incorporate interest already earned by the position so far. * * @param positionId Unique ID of the position * @param addresses Addresses corresponding to: * * [0] = loan payer * [1] = loan taker * [2] = loan position owner * [3] = loan fee recipient * [4] = loan lender fee token * [5] = loan taker fee token * [6] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender * will be >= this amount) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be pulled in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Amount of owedTokens pulled from the lender */ function increasePosition( bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increasePositionImpl( state, positionId, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Increase a position directly by putting up heldToken. The caller will serve as both the * lender and the position owner * * @param positionId Unique ID of the position * @param principalToAdd Principal amount to add to the position * @return Amount of heldToken pulled from the msg.sender */ function increaseWithoutCounterparty( bytes32 positionId, uint256 principalToAdd ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increaseWithoutCounterpartyImpl( state, positionId, principalToAdd ); } /** * Close a position. May be called by the owner or with the approval of the owner. May provide * an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient * is sent the resulting payout. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param exchangeWrapper Address of the exchange wrapper * @param payoutInHeldToken True to pay out the payoutRecipient in heldToken, * False to pay out the payoutRecipient in owedToken * @param order Order object to be passed to the exchange wrapper * @return Values corresponding to: * 1) Principal of position closed * 2) Amount of tokens (heldToken if payoutInHeldtoken is true, * owedToken otherwise) received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePosition( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes order ) external closePositionStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, order ); } /** * Helper to close a position by paying owedToken directly rather than using an exchangeWrapper. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePositionDirectly( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionDirectlyStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, new bytes(0) ); } /** * Reduce the size of a position and withdraw a proportional amount of heldToken from the vault. * Must be approved by both the position owner and lender. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * 3) The amount allowed by the lender if closer != lender * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the msg.sender */ function closeWithoutCounterparty( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionStateControl nonReentrant returns (uint256, uint256) { return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl( state, positionId, requestedCloseAmount, payoutRecipient ); } /** * Margin-call a position. Only callable with the approval of the position lender. After the * call, the position owner will have time equal to the callTimeLimit of the position to close * the position. If the owner does not close the position, the lender can recover the collateral * in the position. * * @param positionId Unique ID of the position * @param requiredDeposit Amount of deposit the position owner will have to put up to cancel * the margin-call. Passing in 0 means the margin call cannot be * canceled by depositing */ function marginCall( bytes32 positionId, uint256 requiredDeposit ) external nonReentrant { LoanImpl.marginCallImpl( state, positionId, requiredDeposit ); } /** * Cancel a margin-call. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position */ function cancelMarginCall( bytes32 positionId ) external onlyWhileOperational nonReentrant { LoanImpl.cancelMarginCallImpl(state, positionId); } /** * Used to recover the heldTokens held as collateral. Is callable after the maximum duration of * the loan has expired or the loan has been margin-called for the duration of the callTimeLimit * but remains unclosed. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return Amount of heldToken recovered */ function forceRecoverCollateral( bytes32 positionId, address recipient ) external nonReentrant returns (uint256) { return ForceRecoverCollateralImpl.forceRecoverCollateralImpl( state, positionId, recipient ); } /** * Deposit additional heldToken as collateral for a position. Cancels margin-call if: * 0 < position.requiredDeposit < depositAmount. Only callable by the position owner. * * @param positionId Unique ID of the position * @param depositAmount Additional amount in heldToken to deposit */ function depositCollateral( bytes32 positionId, uint256 depositAmount ) external onlyWhileOperational nonReentrant { DepositCollateralImpl.depositCollateralImpl( state, positionId, depositAmount ); } /** * Cancel an amount of a loan offering. Only callable by the loan offering's payer. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan position owner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param cancelAmount Amount to cancel * @return Amount that was canceled */ function cancelLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) external cancelLoanOfferingStateControl nonReentrant returns (uint256) { return LoanImpl.cancelLoanOfferingImpl( state, addresses, values256, values32, cancelAmount ); } /** * Transfer ownership of a loan to a new address. This new address will be entitled to all * payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it * must implement the LoanOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the loan */ function transferLoan( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferLoanImpl( state, positionId, who); } /** * Transfer ownership of a position to a new address. This new address will be entitled to all * payouts. Only callable by the owner of a position. If "who" is a contract, it must implement * the PositionOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the position */ function transferPosition( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferPositionImpl( state, positionId, who); } // ============ Public Constant Functions ============ /** * Gets the address of the Vault contract that holds and accounts for tokens. * * @return The address of the Vault contract */ function getVaultAddress() external view returns (address) { return state.VAULT; } /** * Gets the address of the TokenProxy contract that accounts must set allowance on in order to * make loans or open/close positions. * * @return The address of the TokenProxy contract */ function getTokenProxyAddress() external view returns (address) { return state.TOKEN_PROXY; } } // File: contracts/margin/interfaces/OnlyMargin.sol /** * @title OnlyMargin * @author dYdX * * Contract to store the address of the main Margin contract and trust only that address to call * certain functions. */ contract OnlyMargin { // ============ Constants ============ // Address of the known and trusted Margin contract on the blockchain address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Modifiers ============ modifier onlyMargin() { require( msg.sender == DYDX_MARGIN, "OnlyMargin#onlyMargin: Only Margin can call" ); _; } } // File: contracts/margin/external/lib/LoanOfferingParser.sol /** * @title LoanOfferingParser * @author dYdX * * Contract for LoanOfferingVerifiers to parse arguments */ contract LoanOfferingParser { // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes signature ) internal pure returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering; fillLoanOfferingAddresses(loanOffering, addresses); fillLoanOfferingValues256(loanOffering, values256); fillLoanOfferingValues32(loanOffering, values32); loanOffering.signature = signature; return loanOffering; } function fillLoanOfferingAddresses( MarginCommon.LoanOffering memory loanOffering, address[9] addresses ) private pure { loanOffering.owedToken = addresses[0]; loanOffering.heldToken = addresses[1]; loanOffering.payer = addresses[2]; loanOffering.owner = addresses[3]; loanOffering.taker = addresses[4]; loanOffering.positionOwner = addresses[5]; loanOffering.feeRecipient = addresses[6]; loanOffering.lenderFeeToken = addresses[7]; loanOffering.takerFeeToken = addresses[8]; } function fillLoanOfferingValues256( MarginCommon.LoanOffering memory loanOffering, uint256[7] values256 ) private pure { loanOffering.rates.maxAmount = values256[0]; loanOffering.rates.minAmount = values256[1]; loanOffering.rates.minHeldToken = values256[2]; loanOffering.rates.lenderFee = values256[3]; loanOffering.rates.takerFee = values256[4]; loanOffering.expirationTimestamp = values256[5]; loanOffering.salt = values256[6]; } function fillLoanOfferingValues32( MarginCommon.LoanOffering memory loanOffering, uint32[4] values32 ) private pure { loanOffering.callTimeLimit = values32[0]; loanOffering.maxDuration = values32[1]; loanOffering.rates.interestRate = values32[2]; loanOffering.rates.interestPeriod = values32[3]; } } // File: contracts/margin/external/lib/MarginHelper.sol /** * @title MarginHelper * @author dYdX * * This library contains helper functions for interacting with Margin */ library MarginHelper { function getPosition( address DYDX_MARGIN, bytes32 positionId ) internal view returns (MarginCommon.Position memory) { ( address[4] memory addresses, uint256[2] memory values256, uint32[6] memory values32 ) = Margin(DYDX_MARGIN).getPosition(positionId); return MarginCommon.Position({ owedToken: addresses[0], heldToken: addresses[1], lender: addresses[2], owner: addresses[3], principal: values256[0], requiredDeposit: values256[1], callTimeLimit: values32[0], startTimestamp: values32[1], callTimestamp: values32[2], maxDuration: values32[3], interestRate: values32[4], interestPeriod: values32[5] }); } } // File: contracts/margin/external/BucketLender/BucketLender.sol /** * @title BucketLender * @author dYdX * * On-chain shared lender that allows anyone to deposit tokens into this contract to be used to * lend tokens for a particular margin position. * * - Each bucket has three variables: * - Available Amount * - The available amount of tokens that the bucket has to lend out * - Outstanding Principal * - The amount of principal that the bucket is responsible for in the margin position * - Weight * - Used to keep track of each account's weighted ownership within a bucket * - Relative weight between buckets is meaningless * - Only accounts' relative weight within a bucket matters * * - Token Deposits: * - Go into a particular bucket, determined by time since the start of the position * - If the position has not started: bucket = 0 * - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME) * - This is always the highest bucket; no higher bucket yet exists * - Increase the bucket's Available Amount * - Increase the bucket's weight and the account's weight in that bucket * * - Token Withdrawals: * - Can be from any bucket with available amount * - Decrease the bucket's Available Amount * - Decrease the bucket's weight and the account's weight in that bucket * * - Increasing the Position (Lending): * - The lowest buckets with Available Amount are used first * - Decreases Available Amount * - Increases Outstanding Principal * * - Decreasing the Position (Being Paid-Back) * - The highest buckets with Outstanding Principal are paid back first * - Decreases Outstanding Principal * - Increases Available Amount * * * - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from * those buckets for a longer period of time. * - Deposits in the same bucket earn the same interest rate. * - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not * making the maximum interest). * - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket with Available Amount */ contract BucketLender is Ownable, OnlyMargin, LoanOwner, IncreaseLoanDelegator, MarginCallDelegator, CancelMarginCallDelegator, ForceRecoverCollateralDelegator, LoanOfferingParser, LoanOfferingVerifier, ReentrancyGuard { using SafeMath for uint256; using TokenInteract for address; // ============ Events ============ event Deposit( address indexed beneficiary, uint256 bucket, uint256 amount, uint256 weight ); event Withdraw( address indexed withdrawer, uint256 bucket, uint256 weight, uint256 owedTokenWithdrawn, uint256 heldTokenWithdrawn ); event PrincipalIncreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event PrincipalDecreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event AvailableIncreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); event AvailableDecreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); // ============ State Variables ============ /** * Available Amount is the amount of tokens that is available to be lent by each bucket. * These tokens are also available to be withdrawn by the accounts that have weight in the * bucket. */ // Available Amount for each bucket mapping(uint256 => uint256) public availableForBucket; // Total Available Amount uint256 public availableTotal; /** * Outstanding Principal is the share of the margin position's principal that each bucket * is responsible for. That is, each bucket with Outstanding Principal is owed * (Outstanding Principal)*E^(RT) owedTokens in repayment. */ // Outstanding Principal for each bucket mapping(uint256 => uint256) public principalForBucket; // Total Outstanding Principal uint256 public principalTotal; /** * Weight determines an account's proportional share of a bucket. Relative weights have no * meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has * no meaning. However, the relative weight of two accounts within the same bucket is equal to * the accounts' shares in the bucket and are therefore proportional to the payout that they * should expect from withdrawing from that bucket. */ // Weight for each account in each bucket mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount; // Total Weight for each bucket mapping(uint256 => uint256) public weightForBucket; /** * The critical bucket is: * - Greater-than-or-equal-to The highest bucket with Outstanding Principal * - Less-than-or-equal-to the lowest bucket with Available Amount * * It is equal to both of these values in most cases except in an edge cases where the two * buckets are different. This value is cached to find such a bucket faster than looping through * all possible buckets. */ uint256 public criticalBucket = 0; /** * Latest cached value for totalOwedTokenRepaidToLender. * This number updates on the dYdX Margin base protocol whenever the position is * partially-closed, but this contract is not notified at that time. Therefore, it is updated * upon increasing the position or when depositing/withdrawing */ uint256 public cachedRepaidAmount = 0; // True if the position was closed from force-recovering the collateral bool public wasForceClosed = false; // ============ Constants ============ // Unique ID of the position bytes32 public POSITION_ID; // Address of the token held in the position as collateral address public HELD_TOKEN; // Address of the token being lent address public OWED_TOKEN; // Time between new buckets uint32 public BUCKET_TIME; // Interest rate of the position uint32 public INTEREST_RATE; // Interest period of the position uint32 public INTEREST_PERIOD; // Maximum duration of the position uint32 public MAX_DURATION; // Margin-call time-limit of the position uint32 public CALL_TIMELIMIT; // (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position uint32 public MIN_HELD_TOKEN_NUMERATOR; uint32 public MIN_HELD_TOKEN_DENOMINATOR; // Accounts that are permitted to margin-call positions (or cancel the margin call) mapping(address => bool) public TRUSTED_MARGIN_CALLERS; // Accounts that are permitted to withdraw on behalf of any address mapping(address => bool) public TRUSTED_WITHDRAWERS; // ============ Constructor ============ constructor( address margin, bytes32 positionId, address heldToken, address owedToken, uint32[7] parameters, address[] trustedMarginCallers, address[] trustedWithdrawers ) public OnlyMargin(margin) { POSITION_ID = positionId; HELD_TOKEN = heldToken; OWED_TOKEN = owedToken; require( parameters[0] != 0, "BucketLender#constructor: BUCKET_TIME cannot be zero" ); BUCKET_TIME = parameters[0]; INTEREST_RATE = parameters[1]; INTEREST_PERIOD = parameters[2]; MAX_DURATION = parameters[3]; CALL_TIMELIMIT = parameters[4]; MIN_HELD_TOKEN_NUMERATOR = parameters[5]; MIN_HELD_TOKEN_DENOMINATOR = parameters[6]; // Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS uint256 i = 0; for (i = 0; i < trustedMarginCallers.length; i++) { TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true; } for (i = 0; i < trustedWithdrawers.length; i++) { TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true; } // Set maximum allowance on proxy OWED_TOKEN.approve( Margin(margin).getTokenProxyAddress(), MathHelpers.maxUint256() ); } // ============ Modifiers ============ modifier onlyPosition(bytes32 positionId) { require( POSITION_ID == positionId, "BucketLender#onlyPosition: Incorrect position" ); _; } // ============ Margin-Only State-Changing Functions ============ /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * @param addresses Loan offering addresses * @param values256 Loan offering uint256s * @param values32 Loan offering uint32s * @param positionId Unique ID of the position * @param signature Arbitrary bytes * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( Margin(DYDX_MARGIN).containsPosition(POSITION_ID), "BucketLender#verifyLoanOffering: This contract should not open a new position" ); MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32, signature ); // CHECK ADDRESSES assert(loanOffering.owedToken == OWED_TOKEN); assert(loanOffering.heldToken == HELD_TOKEN); assert(loanOffering.payer == address(this)); assert(loanOffering.owner == address(this)); require( loanOffering.taker == address(0), "BucketLender#verifyLoanOffering: loanOffering.taker is non-zero" ); require( loanOffering.feeRecipient == address(0), "BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero" ); require( loanOffering.positionOwner == address(0), "BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero" ); require( loanOffering.lenderFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero" ); require( loanOffering.takerFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero" ); // CHECK VALUES256 require( loanOffering.rates.maxAmount == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect" ); require( loanOffering.rates.minAmount == 0, "BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero" ); require( loanOffering.rates.minHeldToken == 0, "BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero" ); require( loanOffering.rates.lenderFee == 0, "BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero" ); require( loanOffering.rates.takerFee == 0, "BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero" ); require( loanOffering.expirationTimestamp == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: expirationTimestamp is incorrect" ); require( loanOffering.salt == 0, "BucketLender#verifyLoanOffering: loanOffering.salt is non-zero" ); // CHECK VALUES32 require( loanOffering.callTimeLimit == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect" ); require( loanOffering.maxDuration == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect" ); assert(loanOffering.rates.interestRate == INTEREST_RATE); assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD); // no need to require anything about loanOffering.signature return address(this); } /** * Called by the Margin contract when anyone transfers ownership of a loan to this contract. * This function initializes this contract and returns this address to indicate to Margin * that it is willing to take ownership of the loan. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address on success, throw otherwise */ function receiveLoanOwnership( address from, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID); uint256 initialPrincipal = position.principal; uint256 minHeldToken = MathHelpers.getPartialAmount( uint256(MIN_HELD_TOKEN_NUMERATOR), uint256(MIN_HELD_TOKEN_DENOMINATOR), initialPrincipal ); assert(initialPrincipal > 0); assert(principalTotal == 0); assert(from != address(this)); // position must be opened without lending from this position require( position.owedToken == OWED_TOKEN, "BucketLender#receiveLoanOwnership: Position owedToken mismatch" ); require( position.heldToken == HELD_TOKEN, "BucketLender#receiveLoanOwnership: Position heldToken mismatch" ); require( position.maxDuration == MAX_DURATION, "BucketLender#receiveLoanOwnership: Position maxDuration mismatch" ); require( position.callTimeLimit == CALL_TIMELIMIT, "BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch" ); require( position.interestRate == INTEREST_RATE, "BucketLender#receiveLoanOwnership: Position interestRate mismatch" ); require( position.interestPeriod == INTEREST_PERIOD, "BucketLender#receiveLoanOwnership: Position interestPeriod mismatch" ); require( Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken, "BucketLender#receiveLoanOwnership: Not enough heldToken as collateral" ); // set relevant constants principalForBucket[0] = initialPrincipal; principalTotal = initialPrincipal; weightForBucket[0] = weightForBucket[0].add(initialPrincipal); weightForBucketForAccount[0][from] = weightForBucketForAccount[0][from].add(initialPrincipal); return address(this); } /** * Called by Margin when additional value is added onto the position this contract * is lending for. Balance is added to the address that loaned the additional tokens. * * @param payer Address that loaned the additional tokens * @param positionId Unique ID of the position * @param principalAdded Amount that was added to the position * @param lentAmount Amount of owedToken lent * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { Margin margin = Margin(DYDX_MARGIN); require( payer == address(this), "BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position" ); require( !margin.isPositionCalled(POSITION_ID), "BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called" ); // This function is only called after the state has been updated in the base protocol; // thus, the principal in the base protocol will equal the principal after the increase uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID); uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded); // principalTotal was the principal after the previous increase accountForClose(principalTotal.sub(principalBeforeIncrease)); accountForIncrease(principalAdded, lentAmount); assert(principalTotal == principalAfterIncrease); return address(this); } /** * Function a contract must implement in order to let other addresses call marginCall(). * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[caller], "BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted" ); require( depositAmount == 0, // prevents depositing from canceling the margin-call "BucketLender#marginCallOnBehalfOf: Deposit amount must be zero" ); return address(this); } /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[canceler], "BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted" ); return address(this); } /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address /* recoverer */, bytes32 positionId, address recipient ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { return forceRecoverCollateralInternal(recipient); } // ============ Public State-Changing Functions ============ /** * Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if * part of the position has been closed since the last position increase. */ function rebalanceBuckets() external nonReentrant { rebalanceBucketsInternal(); } /** * Allows users to deposit owedToken into this contract. Allowance must be set on this contract * for "token" in at least the amount "amount". * * @param beneficiary The account that will be entitled to this depoit * @param amount The amount of owedToken to deposit * @return The bucket number that was deposited into */ function deposit( address beneficiary, uint256 amount ) external nonReentrant returns (uint256) { Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; require( beneficiary != address(0), "BucketLender#deposit: Beneficiary cannot be the zero address" ); require( amount != 0, "BucketLender#deposit: Cannot deposit zero tokens" ); require( !margin.isPositionClosed(positionId), "BucketLender#deposit: Cannot deposit after the position is closed" ); require( !margin.isPositionCalled(positionId), "BucketLender#deposit: Cannot deposit while the position is margin-called" ); rebalanceBucketsInternal(); OWED_TOKEN.transferFrom( msg.sender, address(this), amount ); uint256 bucket = getCurrentBucket(); uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket)); uint256 weightToAdd = 0; if (effectiveAmount == 0) { weightToAdd = amount; // first deposit in bucket } else { weightToAdd = MathHelpers.getPartialAmount( amount, effectiveAmount, weightForBucket[bucket] ); } require( weightToAdd != 0, "BucketLender#deposit: Cannot deposit for zero weight" ); // update state updateAvailable(bucket, amount, true); weightForBucketForAccount[bucket][beneficiary] = weightForBucketForAccount[bucket][beneficiary].add(weightToAdd); weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd); emit Deposit( beneficiary, bucket, amount, weightToAdd ); return bucket; } /** * Allows users to withdraw their lent funds. An account can withdraw its weighted share of the * bucket. * * While the position is open, a bucket's share is equal to: * Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest) * Held Token: 0 * * After the position is closed, a bucket's share is equal to: * Owed Token: (Available Amount) * Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal) * * @param buckets The bucket numbers to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens * withdrawn will be at least this amount, but not necessarily more. * Withdrawing the same weight from different buckets does not necessarily * return the same amounts from those buckets. In order to withdraw as many * tokens as possible, use the maximum uint256. * @param onBehalfOf The address to withdraw on behalf of * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdraw( uint256[] buckets, uint256[] maxWeights, address onBehalfOf ) external nonReentrant returns (uint256, uint256) { require( buckets.length == maxWeights.length, "BucketLender#withdraw: The lengths of the input arrays must match" ); if (onBehalfOf != msg.sender) { require( TRUSTED_WITHDRAWERS[msg.sender], "BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others" ); } rebalanceBucketsInternal(); // decide if some bucket is unable to be withdrawn from (is locked) // the zero value represents no-lock uint256 lockedBucket = 0; if ( Margin(DYDX_MARGIN).containsPosition(POSITION_ID) && criticalBucket == getCurrentBucket() ) { lockedBucket = criticalBucket; } uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken uint256 maxHeldToken = 0; if (wasForceClosed) { maxHeldToken = HELD_TOKEN.balanceOf(address(this)); } for (uint256 i = 0; i < buckets.length; i++) { uint256 bucket = buckets[i]; // prevent withdrawing from the current bucket if it is also the critical bucket if ((bucket != 0) && (bucket == lockedBucket)) { continue; } (uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket( onBehalfOf, bucket, maxWeights[i], maxHeldToken ); results[0] = results[0].add(owedTokenForBucket); results[1] = results[1].add(heldTokenForBucket); } // Transfer share of owedToken OWED_TOKEN.transfer(msg.sender, results[0]); HELD_TOKEN.transfer(msg.sender, results[1]); return (results[0], results[1]); } /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to this contract by calling * deposit() will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { rebalanceBucketsInternal(); uint256 amount = token.balanceOf(address(this)); if (token == OWED_TOKEN) { amount = amount.sub(availableTotal); } else if (token == HELD_TOKEN) { require( !wasForceClosed, "BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed" ); } token.transfer(to, amount); return amount; } // ============ Public Getter Functions ============ /** * Get the current bucket number that funds will be deposited into. This is also the highest * bucket so far. * * @return The highest bucket and the one that funds will be deposited into */ function getCurrentBucket() public view returns (uint256) { // load variables from storage; Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; uint32 bucketTime = BUCKET_TIME; assert(!margin.isPositionClosed(positionId)); // if position not created, allow deposits in the first bucket if (!margin.containsPosition(positionId)) { return 0; } // return the number of BUCKET_TIME periods elapsed since the position start, rounded-up uint256 startTimestamp = margin.getPositionStartTimestamp(positionId); return block.timestamp.sub(startTimestamp).div(bucketTime).add(1); } /** * Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of * the bucket multiplied by the interest accrued in the position. If the position is closed, * then any outstanding principal will never be repaid in the form of owedToken. * * @param bucket The bucket number * @return The amount of owedToken that this bucket expects to be paid-back if the posi */ function getBucketOwedAmount( uint256 bucket ) public view returns (uint256) { // if the position is completely closed, then the outstanding principal will never be repaid if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) { return 0; } uint256 lentPrincipal = principalForBucket[bucket]; // the bucket has no outstanding principal if (lentPrincipal == 0) { return 0; } // get the total amount of owedToken that would be paid back at this time uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime( POSITION_ID, principalTotal, uint32(block.timestamp) ); // return the bucket's share return MathHelpers.getPartialAmount( lentPrincipal, principalTotal, owedAmount ); } // ============ Internal Functions ============ function forceRecoverCollateralInternal( address recipient ) internal returns (address) { require( recipient == address(this), "BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract" ); rebalanceBucketsInternal(); wasForceClosed = true; return address(this); } // ============ Private Helper Functions ============ /** * Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the * state if part of the position has been closed since the last position increase. */ function rebalanceBucketsInternal() private { // if force-closed, don't update the outstanding principal values; they are needed to repay // lenders with heldToken if (wasForceClosed) { return; } uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID); accountForClose(principalTotal.sub(marginPrincipal)); assert(principalTotal == marginPrincipal); } /** * Updates the state variables at any time. Only does anything after the position has been * closed or partially-closed since the last time this function was called. * * - Increases the available amount in the highest buckets with outstanding principal * - Decreases the principal amount in those buckets * * @param principalRemoved Amount of principal closed since the last update */ function accountForClose( uint256 principalRemoved ) private { if (principalRemoved == 0) { return; } uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID); assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved); uint256 principalToSub = principalRemoved; uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount); uint256 criticalBucketTemp = criticalBucket; // loop over buckets in reverse order starting with the critical bucket for ( uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { assert(bucket <= criticalBucketTemp); // no underflow on bucket uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue; } uint256 availableTemp = MathHelpers.getPartialAmount( principalTemp, principalToSub, availableToAdd ); updateAvailable(bucket, availableTemp, true); updatePrincipal(bucket, principalTemp, false); principalToSub = principalToSub.sub(principalTemp); availableToAdd = availableToAdd.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToSub == 0); assert(availableToAdd == 0); setCriticalBucket(criticalBucketTemp); cachedRepaidAmount = newRepaidAmount; } /** * Updates the state variables when a position is increased. * * - Decreases the available amount in the lowest buckets with available token * - Increases the principal amount in those buckets * * @param principalAdded Amount of principal added to the position * @param lentAmount Amount of owedToken lent */ function accountForIncrease( uint256 principalAdded, uint256 lentAmount ) private { require( lentAmount <= availableTotal, "BucketLender#accountForIncrease: No lending not-accounted-for funds" ); uint256 principalToAdd = principalAdded; uint256 availableToSub = lentAmount; uint256 criticalBucketTemp; // loop over buckets in order starting from the critical bucket uint256 lastBucket = getCurrentBucket(); for ( uint256 bucket = criticalBucket; principalToAdd > 0; bucket++ ) { assert(bucket <= lastBucket); // should never go past the last bucket uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]); if (availableTemp == 0) { continue; } uint256 principalTemp = MathHelpers.getPartialAmount( availableTemp, availableToSub, principalToAdd ); updateAvailable(bucket, availableTemp, false); updatePrincipal(bucket, principalTemp, true); principalToAdd = principalToAdd.sub(principalTemp); availableToSub = availableToSub.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToAdd == 0); assert(availableToSub == 0); setCriticalBucket(criticalBucketTemp); } /** * Withdraw * * @param onBehalfOf The account for which to withdraw for * @param bucket The bucket number to withdraw from * @param maxWeight The maximum weight to withdraw * @param maxHeldToken The total amount of heldToken that has been force-recovered * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdrawSingleBucket( address onBehalfOf, uint256 bucket, uint256 maxWeight, uint256 maxHeldToken ) private returns (uint256, uint256) { // calculate the user's share uint256 bucketWeight = weightForBucket[bucket]; if (bucketWeight == 0) { return (0, 0); } uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf]; uint256 weightToWithdraw = Math.min256(maxWeight, userWeight); if (weightToWithdraw == 0) { return (0, 0); } // update state weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw); weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw); // calculate for owedToken uint256 owedTokenToWithdraw = withdrawOwedToken( bucket, weightToWithdraw, bucketWeight ); // calculate for heldToken uint256 heldTokenToWithdraw = withdrawHeldToken( bucket, weightToWithdraw, bucketWeight, maxHeldToken ); emit Withdraw( onBehalfOf, bucket, weightToWithdraw, owedTokenToWithdraw, heldTokenToWithdraw ); return (owedTokenToWithdraw, heldTokenToWithdraw); } /** * Helper function to withdraw earned owedToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @return The amount of owedToken being withdrawn */ function withdrawOwedToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight ) private returns (uint256) { // amount to return for the bucket uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount( userWeight, bucketWeight, availableForBucket[bucket].add(getBucketOwedAmount(bucket)) ); // check that there is enough token to give back require( owedTokenToWithdraw <= availableForBucket[bucket], "BucketLender#withdrawOwedToken: There must be enough available owedToken" ); // update amounts updateAvailable(bucket, owedTokenToWithdraw, false); return owedTokenToWithdraw; } /** * Helper function to withdraw heldToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @param maxHeldToken The total amount of heldToken available to withdraw * @return The amount of heldToken being withdrawn */ function withdrawHeldToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight, uint256 maxHeldToken ) private returns (uint256) { if (maxHeldToken == 0) { return 0; } // user's principal for the bucket uint256 principalForBucketForAccount = MathHelpers.getPartialAmount( userWeight, bucketWeight, principalForBucket[bucket] ); uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount( principalForBucketForAccount, principalTotal, maxHeldToken ); updatePrincipal(bucket, principalForBucketForAccount, false); return heldTokenToWithdraw; } // ============ Setter Functions ============ /** * Changes the critical bucket variable * * @param bucket The value to set criticalBucket to */ function setCriticalBucket( uint256 bucket ) private { // don't spend the gas to sstore unless we need to change the value if (criticalBucket == bucket) { return; } criticalBucket = bucket; } /** * Changes the available owedToken amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the available amount by * @param increase True if positive change, false if negative change */ function updateAvailable( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = availableTotal.add(amount); newForBucket = availableForBucket[bucket].add(amount); emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = availableTotal.sub(amount); newForBucket = availableForBucket[bucket].sub(amount); emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } availableTotal = newTotal; availableForBucket[bucket] = newForBucket; } /** * Changes the principal amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the principal amount by * @param increase True if positive change, false if negative change */ function updatePrincipal( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = principalTotal.add(amount); newForBucket = principalForBucket[bucket].add(amount); emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = principalTotal.sub(amount); newForBucket = principalForBucket[bucket].sub(amount); emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } principalTotal = newTotal; principalForBucket[bucket] = newForBucket; } } // File: contracts/margin/external/BucketLender/BucketLenderFactory.sol /** * @title BucketLenderFactory * @author dYdX * * Contract that allows anyone to deploy a BucketLender contract by sending a transaction. */ contract BucketLenderFactory { // ============ Events ============ event BucketLenderCreated( address indexed creator, address indexed owner, bytes32 indexed positionId, address at ); // ============ State Variables ============ // Address of the Margin contract for the dYdX Margin Trading Protocol address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Public Functions ============ /** * Deploy a new BucketLender contract to the blockchain * * @param positionId Unique ID of the position * @param owner Address to which ownership of the BucketLender will be transferred * @param heldToken Address of the token held in the position as collateral * @param owedToken Address of the token being lent by the BucketLender * @param parameters Values corresponding to: * * [0] = number of seconds per bucket * [1] = interest rate * [2] = interest period * [3] = maximum loan duration * [4] = margin-call timelimit * [5] = numerator of minimum heldToken-per-owedToken * [6] = denominator of minimum heldToken-per-owedToken * * @param marginCallers Accounts that are permitted to margin-call positions (or cancel the margin call) * @return The address of the new BucketLender contract */ function createBucketLender( bytes32 positionId, address owner, address heldToken, address owedToken, uint32[7] parameters, address[] marginCallers, address[] withdrawers ) external returns (address) { address newBucketLender = new BucketLender( DYDX_MARGIN, positionId, heldToken, owedToken, parameters, marginCallers, withdrawers ); BucketLender(newBucketLender).transferOwnership(owner); emit BucketLenderCreated( msg.sender, owner, positionId, newBucketLender ); return newBucketLender; } }
* Updates the state variables at any time. Only does anything after the position has been closed or partially-closed since the last time this function was called. - Increases the available amount in the highest buckets with outstanding principal - Decreases the principal amount in those buckets @param principalRemoved Amount of principal closed since the last update/
function accountForClose( uint256 principalRemoved ) private { if (principalRemoved == 0) { return; } uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID); assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved); uint256 principalToSub = principalRemoved; uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount); uint256 criticalBucketTemp = criticalBucket; uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue; } uint256 availableTemp = MathHelpers.getPartialAmount( principalTemp, principalToSub, availableToAdd ); updateAvailable(bucket, availableTemp, true); updatePrincipal(bucket, principalTemp, false); principalToSub = principalToSub.sub(principalTemp); availableToAdd = availableToAdd.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToSub == 0); assert(availableToAdd == 0); setCriticalBucket(criticalBucketTemp); cachedRepaidAmount = newRepaidAmount; }
1,594,219
[ 1, 5121, 326, 919, 3152, 622, 1281, 813, 18, 5098, 1552, 6967, 1839, 326, 1754, 711, 2118, 4375, 578, 19976, 17, 12204, 3241, 326, 1142, 813, 333, 445, 1703, 2566, 18, 300, 657, 1793, 3304, 326, 2319, 3844, 316, 326, 9742, 9169, 598, 20974, 8897, 300, 31073, 3304, 326, 8897, 3844, 316, 5348, 9169, 282, 8897, 10026, 225, 16811, 434, 8897, 4375, 3241, 326, 1142, 1089, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 2236, 1290, 4605, 12, 203, 3639, 2254, 5034, 8897, 10026, 203, 565, 262, 203, 3639, 3238, 203, 565, 288, 203, 3639, 309, 261, 26138, 10026, 422, 374, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 394, 426, 29434, 6275, 273, 490, 5243, 12, 40, 61, 28826, 67, 19772, 7702, 2934, 588, 5269, 3494, 329, 1345, 426, 29434, 774, 48, 2345, 12, 15258, 67, 734, 1769, 203, 3639, 1815, 12, 2704, 426, 29434, 6275, 18, 1717, 12, 7097, 426, 29434, 6275, 13, 1545, 8897, 10026, 1769, 203, 203, 3639, 2254, 5034, 8897, 774, 1676, 273, 8897, 10026, 31, 203, 3639, 2254, 5034, 2319, 13786, 273, 394, 426, 29434, 6275, 18, 1717, 12, 7097, 426, 29434, 6275, 1769, 203, 3639, 2254, 5034, 11239, 4103, 7185, 273, 11239, 4103, 31, 203, 203, 5411, 2254, 5034, 2783, 273, 11239, 4103, 7185, 31, 203, 5411, 8897, 774, 1676, 405, 374, 31, 203, 5411, 2783, 413, 203, 3639, 262, 288, 203, 203, 5411, 2254, 5034, 8897, 7185, 273, 2361, 18, 1154, 5034, 12, 26138, 774, 1676, 16, 8897, 1290, 4103, 63, 7242, 19226, 203, 5411, 309, 261, 26138, 7185, 422, 374, 13, 288, 203, 7734, 1324, 31, 203, 5411, 289, 203, 5411, 2254, 5034, 2319, 7185, 273, 2361, 13375, 18, 588, 9447, 6275, 12, 203, 7734, 8897, 7185, 16, 203, 7734, 8897, 774, 1676, 16, 203, 7734, 2319, 13786, 203, 5411, 11272, 203, 203, 5411, 1089, 5268, 12, 7242, 16, 2319, 7185, 16, 638, 1769, 203, 5411, 1089, 9155, 12, 7242, 16, 2 ]
pragma solidity ^0.5.10; /** * @title A Supply Chain prototype contract implementation. * @author Brian Ludlam * @notice All Supply Chain relevant data is stored on-chain, with all data erroneous * to the system stored on IPFS. All information in the system, whether on-chain or on * IPFS, is impossible to change without a contract event logging the change, and all * versions of all data can be permanently referenced on IPFS. * A Supply Chain is defined in this system as a Directed Acyclic Graph of supply steps * that follow the production of something back to it's conception. A supply step always * references a single item in the system, and may extend one or more previous supply steps, * or precedents. A new step may only be added as a first step, or the last step of an existing * supply chain. Approval must be granted to create a new supply step, which extends a supply * step not owned directly. */ contract SupplyChain { /** * Struct IPFile - IPFS file signature data structure. */ struct IPFile { bytes32 digest;//file digest = file hash uint8 meta;//file meta = file hashing algorithm type uint8 size;//file size } /** * Struct SupplyNode - Supply Node data structure. */ struct SupplyNode { address owner;//owner / creator of Supply Node IPFile nodeFile;//IPFS File for Supply Node uint256 steps;//number of Supply Steps setup on this Supply Node mapping(address => bool) operator;//Supply Node Operators } /** * Struct SupplyStep - Supply Step data structure. */ struct SupplyStep { uint256 node;//Origin Supply Node uint256 item;//Referenced Supply Item IPFile stepFile;//IPFS File for Supply Step uint256[] precedents;//preceding Supply Steps to this Supply Step uint256 approvals;//number of Supply Node access approvals for this Supply Step mapping(uint256 => bool) approval;//mapping of Supply Node access approvals } //developer account with primary contract control address payable private _developer; //Supply Node Index uint256 private _nodeIndex; //Supply Node index mapping to SupplyNode data structure mapping(uint256 => SupplyNode) private _supplyNode; //Supply Item Index uint256 _itemIndex; //Supply Item index mapping to IPFS file data structure mapping(uint256 => IPFile) _itemFile; //Supply Item index mapping to origin Supply Node mapping(uint256 => uint256) _itemNode; //Supply Item index mapping to index of it's last Supply Step (zero if none.) mapping(uint256 => uint256) _itemStep; //Supply Step Index uint256 private _stepIndex; //Supply Step mapping from index to SupplyStep data structure mapping(uint256 => SupplyStep) private _supplyStep; /** * Event SupplyNodeAdded - Log each time a new Supply Node is added. * @return nodeId = Supply Node ID * @return owner = Supply Node owner * @return timestamp = Timestamp when Supply Node was added. */ event SupplyNodeAdded( uint256 indexed nodeId, address indexed owner, uint256 timestamp ); /** * Event SupplyNodeRemoved - Log each time a new Supply Node is removed. * @return nodeId = Supply Node ID * @return owner = Supply Node owner * @return timestamp = Timestamp when Supply Node was removed. */ event SupplyNodeRemoved( uint256 indexed nodeId, address indexed owner, uint256 timestamp ); /** * Event NodeOpApproval - Log each change in new Supply Node operator approval status. * @return nodeId = Supply Node ID * @return operator = Supply Node operator * @return approved = Supply Node operator approval status * @return timestamp = Timestamp of Supply Node operator status change. */ event NodeOpApproval( uint256 indexed nodeId, address indexed operator, bool approved, uint256 timestamp ); /** * Event SupplyItemAdded - Log each time a new Supply Item is added. * @return itemId = Supply Item ID that was added. * @return nodeId = Supply Node ID that Supply Item was added to. * @return timestamp = Timestamp when Supply Item was added. */ event SupplyItemAdded( uint256 indexed itemId, uint256 indexed nodeId, uint256 timestamp ); /** * Event SupplyItemRemoved - Log each time a new Supply Item is removed. * @return itemId = Supply Item ID that was removed. * @return nodeId = Supply Node ID that Supply Item was removed from. * @return timestamp = Timestamp when Supply Item was removed. */ event SupplyItemRemoved( uint256 indexed itemId, uint256 indexed nodeId, uint256 timestamp ); /** * Event SupplyStepAdded - Log each time a new Supply Step is added. * @return stepId = Supply Step ID that was added. * @return nodeId = Supply Node ID that Supply Step was added to. * @return itemId = Supply Item ID that Supply Step references. * @return timestamp = Timestamp when Supply Step was added. */ event SupplyStepAdded( uint256 indexed stepId, uint256 indexed nodeId, uint256 indexed itemId, uint256 timestamp ); /** * Event SupplyStepRemoved - Log each time a new Supply Step is removed. * @return stepId = Supply Step ID that was added. * @return nodeId = Supply Node ID that Supply Step was added to. * @return itemId = Supply Item ID that Supply Step references. * @return timestamp = Timestamp when Supply Step was removed. */ event SupplyStepRemoved( uint256 indexed stepId, uint256 indexed nodeId, uint256 indexed itemId, uint256 timestamp ); /** * Event SupplyStepRequest - Log Supply Step access requested by Supply Node. * @return stepId = Supply Step ID being requested for access. * @return owner = Owner of Supply Node requesting access. * @return nodeId = Supply Node ID requesting access. * @return timestamp = Timestamp when Supply Step access was requested. */ event SupplyStepRequest( uint256 indexed stepId, address indexed owner, uint256 indexed nodeId, uint256 timestamp ); /** * Event SupplyNodeApproval - Log Supply Step access approval status change for Supply Node. * @return stepId = Supply Step ID approving access to Supply Node. * @return owner = Owner of Supply Node receiving approval for access. * @return nodeId = Supply Node ID receiving approval for access. * @return approved = Supply Node approval status * @return timestamp = Timestamp when Supply Node access approval status changed. */ event SupplyNodeApproval( uint256 indexed stepId, address indexed owner, uint256 indexed nodeId, bool approved, uint256 timestamp ); //Contract constructor sets developer account control and initializes indexes. constructor() public { _developer = msg.sender; _nodeIndex = _stepIndex = _itemIndex = 0; } /** * Transaction addSupplyNode - Add Supply Node with IPFS file data. * @param fileDigest = IPFS file multihash - hash data part * @param fileMeta = IPFS file multihash - hash algorythm part * @param fileSize = IPFS file multihash - file size part * @return uint256 new Supply Node index value * @notice IPFS File multihash parts must be relatively valid. */ function addSupplyNode ( bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) public returns(uint256) { //Check require (fileDigest != 0x0, "Invalid file digest."); require (fileMeta != 0, "Invalid file meta."); require (fileSize != 0, "Invalid file size."); //Effect IPFile memory nodeFile = IPFile(fileDigest, fileMeta, fileSize); SupplyNode memory newNode = SupplyNode(msg.sender, nodeFile, 0); _supplyNode[++_nodeIndex] = newNode; //Reflect emit SupplyNodeAdded (_nodeIndex, msg.sender, now); return _nodeIndex; } /** * Transaction removeSupplyNode - Remove Supply Node by ID. * @param nodeId = Valid ID of a Supply Node * @return boolean transaction success * @notice must be owner of Supply Node, Supply Node must exist and be inactive. */ function removeSupplyNode (uint256 nodeId) public returns(bool) { //Check require (nodeId != 0, "Node doesn't exist."); SupplyNode storage node = _supplyNode[nodeId]; require (node.owner == msg.sender, "Must be node owner."); require (node.steps == 0, "Cannot remove node with active steps."); //Effect delete _supplyNode[nodeId].nodeFile; delete _supplyNode[nodeId]; //Reflect emit SupplyNodeRemoved (nodeId, msg.sender, now); return true; } /** * Transaction approveNodeOp - Set approval for Supply Node operators by account address. * @param nodeId = Valid ID of a Supply Node * @return boolean transaction success * @notice must be owner of Supply Node. */ function approveNodeOp ( uint256 nodeId, address operator, bool approved ) public returns(bool) { //Check require (_supplyNode[nodeId].owner == msg.sender, "Node owner only."); require (operator != address(0), "Invalid operator address."); //Effect if (_supplyNode[nodeId].operator[operator] != approved) { _supplyNode[nodeId].operator[operator] = approved; } //Reflect emit NodeOpApproval (nodeId, operator, approved, now); return true; } /** * Transaction addSupplyItem - Add Supply Item to Supply Node as IPFS file. * @param nodeId = Origin Supply Node * @param fileDigest = IPFS file multihash - hash data part * @param fileMeta = IPFS file multihash - hash algorythm part * @param fileSize = IPFS file multihash - file size part * @return uint256 new Supply Item index value * @notice Must be Supply Node owner or operator, IPFS File multihash parts * must be relatively valid. */ function addSupplyItem ( uint256 nodeId, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) public returns(uint256) { //Check require (_supplyNode[nodeId].nodeFile.size != 0, "Invalid supply node."); require (_supplyNode[nodeId].owner == msg.sender || _supplyNode[nodeId].operator[msg.sender], "Invalid owner / operator."); require (fileDigest != 0x0, "Invalid file digest."); require (fileMeta != 0, "Invalid file meta."); require (fileSize != 0, "Invalid file size."); //Effect IPFile memory itemFile = IPFile(fileDigest, fileMeta, fileSize); _itemFile[++_itemIndex] = itemFile; _itemNode[_itemIndex] = nodeId; _itemStep[_itemIndex] = 0;//no steps //Reflect emit SupplyItemAdded (_itemIndex, nodeId, now); return _itemIndex; } /** * Transaction removeSupplyItem - Remove Supply Item by ID. * @param itemId = Valid Supply Item ID * @return boolean transaction success * @notice Must be Supply Node owner or operator, Item may not have active * Supply Steps. */ function removeSupplyItem (uint256 itemId) public returns(bool) { //Check require (_itemNode[itemId] == 0 || _itemFile[itemId].size != 0, "Invalid item."); require (_itemStep[itemId] == 0, "Cannot remove item with active steps."); uint256 nodeId = _itemNode[itemId]; require (_supplyNode[nodeId].nodeFile.size != 0, "Invalid supply item root node."); require (_supplyNode[nodeId].owner == msg.sender || _supplyNode[nodeId].operator[msg.sender], "Invalid owner / operator."); //Effect delete _itemFile[itemId]; delete _itemStep[itemId]; delete _itemNode[itemId]; //Reflect emit SupplyItemRemoved (itemId, nodeId, now); return true; } /** * Transaction addSupplyStep - Add Supply Step for Supply Item at Supply Node. * @param nodeId = Supply Node to end Supply Step to. * @param itemId = Supply Item this Supply Step references. * @param precedents = Array of Supply Step IDs, which this Supply Step extends. * @param fileDigest = IPFS file multihash - hash data part * @param fileMeta = IPFS file multihash - hash algorythm part * @param fileSize = IPFS file multihash - file size part * @return uint256 new supply step index value * @notice Must be valid Supply Step (see validateSupplyStep(), IPFS File * multihash parts must be relatively valid. */ function addSupplyStep ( uint256 nodeId, uint256 itemId, uint256[] memory precedents, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) public returns(uint256) { //Check require (fileDigest != 0x0, "Invalid file digest."); require (fileMeta != 0, "Invalid file meta."); require (fileSize != 0, "Invalid file size."); require (validateSupplyStep(nodeId, itemId, precedents), "Invalid Supply Step."); //Effect IPFile memory stepFile = IPFile(fileDigest, fileMeta, fileSize); SupplyStep memory newStep = SupplyStep(nodeId, itemId, stepFile, precedents, 0); _supplyStep[++_stepIndex] = newStep; _itemStep[itemId] = _stepIndex; _supplyNode[nodeId].steps += 1; //Reflect emit SupplyStepAdded (_stepIndex, nodeId, itemId, now); return _stepIndex; } /** * Transaction removeSupplyStep - Remove Supply Step by ID. * @param stepId = Valid Supply Step ID * @return boolean transaction success * @notice Must be Supply Node owner or operator, must be Supply Items's * last Supply Step, must not have any active Supply Node approvals. */ function removeSupplyStep (uint256 stepId) public returns(bool) { //Check SupplyStep storage step = _supplyStep[stepId]; uint256 nodeId = step.node; uint256 itemId = step.item; require (nodeId != 0, "Invalid step."); require (_supplyNode[nodeId].owner == msg.sender || _supplyNode[nodeId].operator[msg.sender], "Invalid owner / operator."); require (_itemStep[itemId] == stepId, "Only item's last step removable."); require (step.approvals == 0, "Cannot remove step with active approvals."); //Effect if (step.precedents.length > 0) { //reset itemStep to previous itemStep if exists in precedents. uint8 index = 0; while (index < step.precedents.length) { if (_supplyStep[step.precedents[index]].item == itemId) { _itemStep[itemId] = step.precedents[index]; break;//can only be one } else index++; } if (index == step.precedents.length) _itemStep[itemId] = 0; }else _itemStep[itemId] = 0; if (_supplyNode[nodeId].steps > 0) _supplyNode[nodeId].steps -= 1; delete _supplyStep[stepId].stepFile; delete _supplyStep[stepId]; //Reflect emit SupplyStepRemoved (stepId, nodeId, itemId, now); return true; } /** * Transaction requestSupplyStep - Request for Supply Node access to existing Supply Step. * @param stepId = Valid ID of a Supply Step beign requested. * @param nodeId = Valid ID of a Supply Node doing the requesting. * @return boolean transaction success * @notice Must be owner of Supply Node doing the request. Event-only effect, * address of Supply Step's Supply Node owner included for event trigger. */ function requestSupplyStep ( uint256 stepId, uint256 nodeId ) public returns(bool) { //Check require (_supplyStep[stepId].node != 0, "Invalid step."); require (_supplyNode[nodeId].owner == msg.sender, "Node owner only."); //Reflect emit SupplyStepRequest ( stepId, _supplyNode[_supplyStep[stepId].node].owner, nodeId, now ); return true; } /** * Transaction approveSupplyNode - Set approval for Supply Node access to existing * Supply Step. * @param stepId = Valid ID of a Supply Step approving. * @param nodeId = Valid ID of a Supply Node being approved. * @param approved = State of approval. * @return boolean transaction success * @notice Must be owner of Supply Node owning Supply Step doing the approval. * . */ function approveSupplyNode ( uint256 stepId, uint256 nodeId, bool approved ) public returns(bool) { //Check uint256 stepNode = _supplyStep[stepId].node; require (stepNode != 0, "Invalid step."); require (_supplyNode[stepNode].owner == msg.sender, "Step Node owner only."); //Effect if (_supplyStep[stepId].approval[nodeId] != approved) { _supplyStep[stepId].approval[nodeId] = approved; if (approved) _supplyStep[stepId].approvals += 1; else if (_supplyStep[stepId].approvals > 0) _supplyStep[stepId].approvals -= 1; } //Reflect emit SupplyNodeApproval (stepId, msg.sender, nodeId, approved, now); return true; } /** * View supplyNode - Get Supply Node data by ID. * @param nodeId = Valid ID of a Supply Node. * @return owner = Supply Node owner address. * @return fileDigest = Node File - IPFS file multihash - hash data part * @return fileMeta = Node File - IPFS file multihash - hash algorythm part * @return fileSize = Node File - IPFS file multihash - file size part * */ function supplyNode(uint256 nodeId) external view returns (address owner, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) { owner = _supplyNode[nodeId].owner; fileDigest = _supplyNode[nodeId].nodeFile.digest; fileMeta = _supplyNode[nodeId].nodeFile.meta; fileSize = _supplyNode[nodeId].nodeFile.size; } /** * View supplyItem - Get Supply Item data by ID. * @param itemId = Valid ID of a Supply Item. * @return nodeId =ID of Supply Item's origin Supply Node. * @return lastStep = Supply Item's last Supply Step ID. (zero if none) * @return fileDigest = Item File - IPFS file multihash - hash data part * @return fileMeta = Item File - IPFS file multihash - hash algorythm part * @return fileSize = Item File - IPFS file multihash - file size part * */ function supplyItem(uint256 itemId) external view returns (uint256 nodeId, uint256 lastStep, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) { nodeId = _itemNode[itemId]; lastStep = _itemStep[itemId]; fileDigest = _itemFile[itemId].digest; fileMeta = _itemFile[itemId].meta; fileSize = _itemFile[itemId].size; } /** * View supplyStep - Get Supply Step data by ID. * @param stepId = Valid ID of a Supply Step. * @return nodeId = ID of Supply Step's Supply Item's origin Supply Node. * @return itemId = Supply Item referenced by Supply Step. * @return precedents = Array of Supply Step IDs, which this Supply Step extends. * @return fileDigest = Step File - IPFS file multihash - hash data part * @return fileMeta = Step File - IPFS file multihash - hash algorythm part * @return fileSize = Step File - IPFS file multihash - file size part * */ function supplyStep(uint256 stepId) external view returns ( uint256 nodeId, uint256 itemId, uint256[] memory precedents, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) { nodeId = _supplyStep[stepId].node; itemId = _supplyStep[stepId].item; precedents = _supplyStep[stepId].precedents; fileDigest = _supplyStep[stepId].stepFile.digest; fileMeta = _supplyStep[stepId].stepFile.meta; fileSize = _supplyStep[stepId].stepFile.size; } /** * View validateSupplyStep - Validates a potential Supply Step entry to see if it's valid. * @param nodeId = ID of Supply Supply Node to create Supply Step on. * @param itemId = Supply Item referenced by Supply Step. * @param precedents = Array of Supply Step IDs, which this Supply Step extends. * @return boolean = valid or not * @notice this check always occurs before adSupplyStep transaction, however can be called * independently first to check vaidiity, to avoid transaction fail. * Checks: Node is valid, sender is owner or operator of Supply Node adding the step, * item referenced is valid, all included precedents are themselves last steps of there * respective items, the nodeId adding them has approval to extend those steps, and adding * a step that is not the first step of a given item, must include that item's last step * as a precedent, given approval to do so. * */ function validateSupplyStep ( uint256 nodeId, uint256 itemId, uint256[] memory precedents ) public view returns(bool) { if (_supplyNode[nodeId].nodeFile.size == 0) return false; if (_supplyNode[nodeId].owner != msg.sender && !_supplyNode[nodeId].operator[msg.sender]) return false; if (_itemFile[itemId].size == 0) return false; uint8 itemRepeatStep = 0; if (precedents.length > 0) { uint8 index = 0; while (index < precedents.length) { if (_supplyStep[precedents[index]].item == 0 || !(_supplyStep[precedents[index]].node == nodeId || _supplyStep[precedents[index]].approval[nodeId]) || _itemStep[_supplyStep[precedents[index]].item] != precedents[index]) { return false; } if (_supplyStep[precedents[index]].item == itemId) itemRepeatStep++; index++; } } if (itemRepeatStep > 1 || (itemRepeatStep == 0 && _itemStep[itemId] != 0)) return false; return true; } /** * View isNodeOp - Check address as Node operator. * @param nodeId = Valid ID of a Supply Node. * @param operator = account address. * @return boolean = is node operator * @notice Supply Node owner only */ function isNodeOp(uint256 nodeId, address operator) external view returns (bool) { require (_supplyNode[nodeId].owner == msg.sender); return _supplyNode[nodeId].operator[operator]; } /** * View itemLastStep - Get last Supply Step of given Supply Item ID * @param itemId = Valid ID of a Supply Item. * @return stepId = Supply Step ID */ function itemLastStep(uint256 itemId) public view returns (uint256 stepId) { stepId = _itemStep[itemId]; } /** * View stepPrecedents - Get precedents of given Supply Step ID * @param stepId = Valid ID of a Supply Step. * @return precedents = Array of Supply Step IDs */ function stepPrecedents(uint256 stepId) public view returns (uint256[] memory precedents) { precedents = _supplyStep[stepId].precedents; } /** * View stepNodeApproved - Get Supply Step approval status for Supply Node * @param stepId = Valid ID of a Supply Step. * @param nodeId = Valid ID of a Supply Node. * @return approved = Boolean approval status */ function stepNodeApproved(uint256 stepId, uint256 nodeId) external view returns (bool approved) { approved = (_supplyStep[stepId].node == nodeId || _supplyStep[stepId].approval[nodeId]); } //developer only destroy method function destroy() external { require (_developer == msg.sender); selfdestruct(_developer); } //Return to sender, any abstract transfers function () external payable { msg.sender.transfer(msg.value); } }
preceding Supply Steps to this Supply Step
uint256[] precedents;
15,838,659
[ 1, 1484, 3263, 310, 3425, 1283, 7780, 1121, 358, 333, 3425, 1283, 8693, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 8526, 10575, 4877, 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, -100, -100 ]
./full_match/80001/0xa114Ef31a6A1F66b3129A175980aCD697D3257aa/sources/contracts/Boxes.sol
/ the contest id that made this request fetch the contest object from the id set the random values of the contest flag that chainlink has provided this contest with random values save the contest emit an event
function fulfillRandomWords( uint256 requestId, /* requestId */ uint256[] memory randomWords ) internal override { uint256 contestId = vrfScoreAssignments[requestId]; Contest memory contest = contests[contestId]; contest.randomValues = randomWords; contest.randomValuesSet = true; contests[contestId] = contest; emit RandomValuesReceived(contest.id); }
5,585,395
[ 1, 19, 326, 466, 395, 612, 716, 7165, 333, 590, 2158, 326, 466, 395, 733, 628, 326, 612, 444, 326, 2744, 924, 434, 326, 466, 395, 2982, 716, 2687, 1232, 711, 2112, 333, 466, 395, 598, 2744, 924, 1923, 326, 466, 395, 3626, 392, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22290, 8529, 7363, 12, 203, 3639, 2254, 5034, 14459, 16, 1748, 14459, 1195, 203, 3639, 2254, 5034, 8526, 3778, 2744, 7363, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2254, 5034, 466, 395, 548, 273, 20466, 7295, 18628, 63, 2293, 548, 15533, 203, 3639, 1816, 395, 3778, 466, 395, 273, 466, 25563, 63, 1213, 395, 548, 15533, 203, 3639, 466, 395, 18, 9188, 1972, 273, 2744, 7363, 31, 203, 3639, 466, 395, 18, 9188, 1972, 694, 273, 638, 31, 203, 3639, 466, 25563, 63, 1213, 395, 548, 65, 273, 466, 395, 31, 203, 3639, 3626, 8072, 1972, 8872, 12, 1213, 395, 18, 350, 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 ]
pragma solidity ^0.4.24; import "truffle/Assert.sol"; import "../contracts/ErrorReporter.sol"; contract ErrorReporterTest is ErrorReporter { function testZeroIsNoError() public { Error err = Error.NO_ERROR; Assert.equal(uint(err), 0, "zero must be no error"); } function testOneIsOpaqueError() public { Error err = Error.OPAQUE_ERROR; Assert.equal(uint(err), 1, "one must be indicator of opaque error"); } function testAnotherErrorIsNonZero() public { Error err = Error.INTEGER_OVERFLOW; Assert.isAbove(uint(err), 1, "integer overflow should be above one"); } function testFail() public { Error err = Error.INTEGER_UNDERFLOW; FailureInfo info = FailureInfo.SUPPLY_TRANSFER_IN_FAILED; // Make sure our inputs aren't letting us do a bogus validation Assert.notEqual(uint(err), uint(info), "bad setup: use a FailureInfo with a uint value that differs from the Error's uint value"); Assert.equal(fail(err, info), uint(err), "should return uint value of enum after fail"); } }
Make sure our inputs aren't letting us do a bogus validation
function testFail() public { Error err = Error.INTEGER_UNDERFLOW; FailureInfo info = FailureInfo.SUPPLY_TRANSFER_IN_FAILED; Assert.notEqual(uint(err), uint(info), "bad setup: use a FailureInfo with a uint value that differs from the Error's uint value"); Assert.equal(fail(err, info), uint(err), "should return uint value of enum after fail"); }
13,001,993
[ 1, 6464, 3071, 3134, 4540, 11526, 1404, 2231, 1787, 584, 741, 279, 324, 28774, 3379, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 3754, 1435, 1071, 288, 203, 3639, 1068, 393, 273, 1068, 18, 14217, 67, 31625, 17430, 31, 203, 3639, 13436, 966, 1123, 273, 13436, 966, 18, 13272, 23893, 67, 16596, 6553, 67, 706, 67, 11965, 31, 203, 203, 3639, 5452, 18, 902, 5812, 12, 11890, 12, 370, 3631, 2254, 12, 1376, 3631, 315, 8759, 3875, 30, 999, 279, 13436, 966, 598, 279, 2254, 460, 716, 21944, 628, 326, 1068, 1807, 2254, 460, 8863, 203, 203, 3639, 5452, 18, 9729, 12, 6870, 12, 370, 16, 1123, 3631, 2254, 12, 370, 3631, 315, 13139, 327, 2254, 460, 434, 2792, 1839, 2321, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "../../access/IOwnable.sol"; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; /** * @dev Minimal implementation https://eips.ethereum.org/EIPS/eip-721[ERC721] * Non-Fungible Token Standard. * * ███╗ ███╗██╗███╗ ██╗███████╗████████╗ * ████╗ ████║██║████╗ ██║██╔════╝╚══██╔══╝ * ██╔████╔██║██║██╔██╗ ██║█████╗ ██║ * ██║╚██╔╝██║██║██║╚██╗██║██╔══╝ ██║ * ██║ ╚═╝ ██║██║██║ ╚████║██║ ██║ * ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ * */ contract MiNFT is Initializable, IERC165, IERC721, IERC721Metadata, IOwnable { // Contract & token owner address public override owner; // Token name string public override name; // Token name string public override symbol; // Optional base URI string public baseURI; // Total supply of tokens uint16 public totalSupply; // Mapping of tokenIds to token metadata mapping(uint16 => string) private _mintedTokens; // ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ ██████╗ ██████╗ // ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗ // ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ ██║ ██║██████╔╝ // ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ ██║ ██║██╔══██╗ // ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ ╚██████╔╝██║ ██║ // ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() initializer { owner = msg.sender; } function initialize(string memory name_, string memory symbol_) public initializer { owner = msg.sender; name = name_; symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IOwnable).interfaceId ; } modifier onlyOwner() { require(msg.sender == owner, 'X'); _; } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ /** * @dev Mints `tokenId` and transfers it to `owner()`. * * Emits a {Transfer} event. */ function mint(uint16 tokenId, string memory metadataURI) public onlyOwner { require(!_exists(tokenId), '?'); require(bytes(metadataURI).length > 0, '0'); _mintedTokens[tokenId] = metadataURI; totalSupply += 1; emit Transfer(address(0), owner, tokenId); } /** * @dev Destroys `tokenId`. * * Emits a {Transfer} event. */ function burn(uint16 tokenId) public onlyOwner { require(_exists(tokenId), '?'); delete _mintedTokens[tokenId]; totalSupply -= 1; emit Transfer(owner, address(0), tokenId); } // ███╗ ███╗███████╗████████╗ █████╗ ██████╗ █████╗ ████████╗ █████╗ // ████╗ ████║██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗ // ██╔████╔██║█████╗ ██║ ███████║██║ ██║███████║ ██║ ███████║ // ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██║██╔══██║ ██║ ██╔══██║ // ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║██████╔╝██║ ██║ ██║ ██║ ██║ // ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), '?'); string memory metadataURI; string memory _tokenURI = _mintedTokens[uint16(tokenId)]; if (bytes(baseURI).length == 0) { metadataURI = _tokenURI; } else { metadataURI = string(abi.encodePacked(baseURI, _tokenURI)); } return metadataURI; } /** * @dev Updates a token's metadata URI. */ function setTokenURI(uint16 tokenId, string memory metadataURI) public onlyOwner { require(_exists(tokenId), '?'); _mintedTokens[tokenId] = metadataURI; } /** * @dev Updates contract base URI. */ function setBaseURI(string memory newURI) public onlyOwner { baseURI = newURI; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address wallet) public view virtual override returns (uint256) { require(wallet != address(0)); return wallet == owner ? totalSupply : 0; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId)); return owner; } /** * @dev Returns whether `tokenId` exists. * * 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 bytes(_mintedTokens[uint16(tokenId)]).length > 0; } // ██████╗ ███████╗ █████╗ ██████╗ ██████╗ ███╗ ██╗██╗ ██╗ ██╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔═══██╗████╗ ██║██║ ╚██╗ ██╔╝ // ██████╔╝█████╗ ███████║██║ ██║█████╗██║ ██║██╔██╗ ██║██║ ╚████╔╝ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║╚════╝██║ ██║██║╚██╗██║██║ ╚██╔╝ // ██║ ██║███████╗██║ ██║██████╔╝ ╚██████╔╝██║ ╚████║███████╗██║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝╚═╝ // // https://eips.ethereum.org/EIPS/eip-721 Read only NFT registry. /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256) public view virtual override returns (address) { return address(0); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address, address) public view virtual override returns (bool) { return false; } /** * @dev See {IERC721-approve}. */ function approve(address, uint256) public virtual override { revert('X'); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address, bool) public virtual override { revert('X'); } /** * @dev See {IERC721-setApprovalForAll}. */ function transferFrom(address, address, uint256) public virtual override { revert('X'); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address, address, uint256) public virtual override { revert('X'); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address, address, uint256, bytes memory) public virtual override { revert('X'); } }
* @dev See {IERC721-safeTransferFrom}./
function safeTransferFrom(address, address, uint256, bytes memory) public virtual override { revert('X'); }
13,103,936
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 4626, 5912, 1265, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 5912, 1265, 12, 2867, 16, 1758, 16, 2254, 5034, 16, 1731, 3778, 13, 1071, 5024, 3849, 288, 203, 3639, 15226, 2668, 60, 8284, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } contract SBX_STAKE is Owned{ using SafeMath for uint256; uint256 public penaltyFee = 5; //5% penlaty fee applicable before lock up time uint256 public totalRewards; uint256 public totalStakes; uint256 public firstYearRate = 20; uint256 public secondYearRate = 15; uint256 public afterSecondYearRate = 10; uint256 public firstYearStakingPeriod = 1 weeks; uint256 public secondYearStakingPeriod = 3 days; uint256 public afterSecondYearStakingPeriod = 24 hours; uint256 private contractStartDate; address constant SBX = 0xDaF8a0E12fc3b109A17ED5CbB943A8f3f86081f7; struct DepositedToken{ bool Exist; uint256 activeDeposit; uint256 totalDeposits; uint256 startTime; uint256 pendingGains; uint256 lastClaimedDate; uint256 totalGained; address referrer; } mapping(address => DepositedToken) users; event Staked(address staker, uint256 tokens); event AddedToExistingStake(uint256 tokens); event TokensClaimed(address claimer, uint256 stakedTokens); event RewardClaimed(address claimer, uint256 reward); //#########################################################################################################################################################// //####################################################STAKING EXTERNAL FUNCTIONS###########################################################################// //#########################################################################################################################################################// constructor() public{ contractStartDate = block.timestamp; } // ------------------------------------------------------------------------ // Start staking // @param _tokenAddress address of the token asset // @param _amount amount of tokens to deposit // ------------------------------------------------------------------------ function STAKE(uint256 _amount, address _referrerID) public { require(_referrerID == address(0) || users[_referrerID].Exist, "Invalid Referrer Id"); require(_amount > 0, "Invalid amount"); // add new stake _newDeposit(SBX, _amount, _referrerID); // update referral reward _updateReferralReward(_amount, _referrerID); // transfer tokens from user to the contract balance require(ERC20Interface(SBX).transferFrom(msg.sender, address(this), _amount)); emit Staked(msg.sender, _amount); } // ------------------------------------------------------------------------ // Claim reward and staked tokens // @required user must be a staker // @required must be claimable // ------------------------------------------------------------------------ function ClaimStakedTokens() external { require(users[msg.sender].activeDeposit > 0, "no running stake"); uint256 _penaltyFee = 0; if(users[msg.sender].startTime + latestStakingPeriod() > now){ // claiming before lock up time _penaltyFee = penaltyFee; } uint256 toTransfer = users[msg.sender].activeDeposit.sub(_onePercent(users[msg.sender].activeDeposit).mul(_penaltyFee)); // transfer staked tokens - apply 5% penalty and send back staked tokens require(ERC20Interface(SBX).transfer(msg.sender, toTransfer)); // check if we have any pending reward, add it to pendingGains var users[msg.sender].pendingGains = pendingReward(msg.sender); emit TokensClaimed(msg.sender, toTransfer); // update amount users[msg.sender].activeDeposit = 0; } // ------------------------------------------------------------------------ // Claim reward and staked tokens // @required user must be a staker // @required must be claimable // ------------------------------------------------------------------------ function ClaimReward() public { require(pendingReward(msg.sender) > 0, "nothing pending to claim"); // transfer the reward to the claimer require(ERC20Interface(SBX).transfer(msg.sender, pendingReward(msg.sender))); emit RewardClaimed(msg.sender, pendingReward(msg.sender)); // add claimed reward to global stats totalRewards = totalRewards.add(pendingReward(msg.sender)); // add the reward to total claimed rewards users[msg.sender].totalGained = users[msg.sender].totalGained.add(pendingReward(msg.sender)); // update lastClaim amount users[msg.sender].lastClaimedDate = now; // reset previous rewards users[msg.sender].pendingGains = 0; } //#########################################################################################################################################################// //####################################################STAKING QUERIES######################################################################################// //#########################################################################################################################################################// // ------------------------------------------------------------------------ // Query to get the pending reward // ------------------------------------------------------------------------ function pendingReward(address _caller) public view returns(uint256 _pendingReward){ uint256 _totalStakedTime = 0; uint256 expiryDate = (latestStakingPeriod()).add(users[_caller].startTime); if(now < expiryDate) _totalStakedTime = now.sub(users[_caller].lastClaimedDate); else{ if(users[_caller].lastClaimedDate >= expiryDate) // if claimed after expirydate already _totalStakedTime = 0; else _totalStakedTime = expiryDate.sub(users[_caller].lastClaimedDate); } uint256 _reward_token_second = ((latestStakingRate()).mul(10 ** 21)).div(365 days); // added extra 10^21 uint256 reward = ((users[_caller].activeDeposit).mul(_totalStakedTime.mul(_reward_token_second))).div(10 ** 23); // remove extra 10^21 // the two extra 10^2 is for 100 (%) return (reward.add(users[_caller].pendingGains)); } // ------------------------------------------------------------------------ // Query to get the active stake of the user // ------------------------------------------------------------------------ function yourActiveStake(address _user) public view returns(uint256 _activeStake){ return users[_user].activeDeposit; } // ------------------------------------------------------------------------ // Query to get the total stakes of the user // ------------------------------------------------------------------------ function yourTotalStakesTillToday(address _user) public view returns(uint256 _totalStakes){ return users[_user].totalDeposits; } // ------------------------------------------------------------------------ // Query to get the time of last stake of user // ------------------------------------------------------------------------ function StakedOn(address _user) public view returns(uint256 _unixLastStakedTime){ return users[_user].startTime; } // ------------------------------------------------------------------------ // Query to get total earned rewards from stake // ------------------------------------------------------------------------ function totalStakeRewardsClaimedTillToday(address _user) public view returns(uint256 _totalEarned){ return users[_user].totalGained; } // ------------------------------------------------------------------------ // Query to get the staking rate // ------------------------------------------------------------------------ function latestStakingRate() public view returns(uint256 APY){ uint256 yearOfContract = (((block.timestamp).sub(contractStartDate)).div(365 days)).add(1); uint256 rate; if(yearOfContract == 1) rate = firstYearRate; else if(yearOfContract == 2) rate = secondYearRate; else rate = afterSecondYearRate; return rate; } // ------------------------------------------------------------------------ // Query to get the staking period // ------------------------------------------------------------------------ function latestStakingPeriod() public view returns(uint256 Period){ uint256 yearOfContract = (((block.timestamp).sub(contractStartDate)).div(365 days)).add(1); uint256 period; if(yearOfContract == 1) period = firstYearStakingPeriod; else if(yearOfContract == 2) period = secondYearStakingPeriod; else period = afterSecondYearStakingPeriod; return period; } // ------------------------------------------------------------------------ // Query to get the staking time left // ------------------------------------------------------------------------ function stakingTimeLeft(address _user) public view returns(uint256 _secsLeft){ if(users[_user].activeDeposit > 0){ uint256 left = 0; uint256 expiryDate = (latestStakingPeriod()).add(StakedOn(_user)); if(now < expiryDate) left = expiryDate.sub(now); return left; } else return 0; } //#########################################################################################################################################################// //################################################################COMMON UTILITIES#########################################################################// //#########################################################################################################################################################// // ------------------------------------------------------------------------ // Internal function to add new deposit // ------------------------------------------------------------------------ function _newDeposit(address _tokenAddress, uint256 _amount, address _referrerID) internal{ require(users[msg.sender].activeDeposit == 0, "Already running"); require(_tokenAddress == SBX, "Only SBX tokens supported"); // add that token into the contract balance // check if we have any pending reward, add it to pendingGains variable users[msg.sender].pendingGains = pendingReward(msg.sender); users[msg.sender].activeDeposit = _amount; users[msg.sender].totalDeposits = users[msg.sender].totalDeposits.add(_amount); users[msg.sender].startTime = now; users[msg.sender].lastClaimedDate = now; users[msg.sender].referrer = _referrerID; users[msg.sender].Exist = true; totalStakes = totalStakes.add(_amount); } // ------------------------------------------------------------------------ // Calculates onePercent of the uint256 amount sent // ------------------------------------------------------------------------ function _onePercent(uint256 _tokens) internal pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } // ------------------------------------------------------------------------ // Updates the reward for referrer // ------------------------------------------------------------------------ function _updateReferralReward(uint256 _amount, address _referrerID) private{ users[_referrerID].pendingGains += _onePercent(_amount); } }
check if we have any pending reward, add it to pendingGains var
users[msg.sender].pendingGains = pendingReward(msg.sender);
44,463
[ 1, 1893, 309, 732, 1240, 1281, 4634, 19890, 16, 527, 518, 358, 4634, 43, 4167, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 3677, 63, 3576, 18, 15330, 8009, 9561, 43, 4167, 273, 4634, 17631, 1060, 12, 3576, 18, 15330, 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 ]
// SPDX-License-Identifier: GPL-3.0 /** * @title Complete the Punks: Project * @dev Per-project contract for managing Bodies + Legs * @author earlybail.eth | Cranky Brain Labs * @notice #GetBodied #LegsFuknGooo */ /* ;╟██▓▒ :╟██▓▒ ,φ▒╣╬╬╩╩Γ ╙╩╬╬╬▓▒░ ,╓φ╣▓█╬Γ ╚╣█▓╬▒╓, ,,╓╓╓╓, φ╣▓▓╬╩"" ""╚╣▓▓▒░ ]╟▓████▓▒ φφ╬╬╬╬╩╙ '╚╩╬╬╬▒▒░ φ╫███▓╬╬╬▓▒░ ]╟▓█▓▒ :╟▓█▓▒ φ╫██╬▒ ╚╣█▓╬φ,, :╟██▓▒ :╟██▓▒ φ╫██▓▒ "╙╠╣▓▓▒░ :╟██▓▒ :╟██▓▒ φφ▒▒▒▒╬╬╬╩╩' φ╫██▓▒ :╟██▓▒ ,,, :╟██▓▒ ]╟▓████▓╬⌐ φ╫██▓▒ :╟██▓▒ .╠╣▓▓▒ :╟██▓▒ :╟███╬╩"' φ╫██▓▒ :╟██▓▒ :╟██▓▒ φφ▒φ░ ,φ▒▒░ :╟██▓▒ :╟██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ '╠▓█▓▒ ╚╣█▓╬⌐:╟███▒≥, '╠▓█▓╬≥, ,,φ╣██╬░ :╟██▓▒ :╟██▓▒ ^"╙"' "╙╙" :╟█████▓▒~ ^"╙╠╣▓▓▒~ φ╣▓▓╬╩╙" :╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ╠▓██╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟███▒ ╚╟▓█╬▒╓╠▓██╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╚╣▓▓████╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬╬████╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟███▒╓, ╚╣██╬⌐ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟█████▓▒~ '"╙╙" ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ≤φ▒╬╬╬╬╚ :╟██▓▒ :╟██▓▒ :╟███▒ ╚╣██╬▒,,,,,,,φ╟▓█▓╩ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╩╬╣▓▓▓▓▓▓▓▓╬╬╚╙' :╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬▓▓▓▓▓▓▓╬╩░ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ ]φ╣▓▒░ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╠╬▓╩░ :╟██▓▒ :╟███▒, :╟██▓▒ :╟██▓▒ :╟████▓▒▒ :╟██▓▒ :╟██▓▒ ╚╬█████▓▒▒╣██▓▒ :╟██▓▒ "╠▓████████▓▒ :╟██▓▒ */ /* φ╫██▓▒ :╟██▓▒ φ╫██▓▒ ,φ▒▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒░ :╟██▓▒ φ╫██▓▒ φ╣███████████████▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓╩╙╙╙╙╙╙╙╚╣██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ "╩╬▓╬▒φφ, :╟██▓▒ ╚╬▓╬╬▒φε φ╫██▓▒ 7╟▓█▓▒, ;╟██▓▒ `╠╣█▓╬░ φ╫██▓▒ "╙╩╬╣▓▓▓▓▓███▓▒ ^╙╩╬╣▓▓▓▓▓▒░ φ╫██▓▒ ╚╠╣███████▓▒ "╠╬████╬╬▒φε φ╫██▓▒ ```╠╠███▒, ```░╠╣██╬[ φ╫████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████╬[ "╠╬███████████████████████████████████████████████╬╩ `^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ // Directives. pragma solidity 0.8.9; // Third-party deps. import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; // Local deps. import "./Bodies.sol"; import "./Legs.sol"; // Contract. contract Project is ReentrancyGuard, Ownable, PaymentSplitter { // Events. event StatusChange(Status _newStatus); // Mint statuses. enum Status { Paused, Whitelist, Mintpass, Public } // Current mint status, defaults to Status[0] (Paused). Status public status; // Bodies. Bodies public bodies; // Legs. Legs public legs; // Pricing. // @notice settable, use mintPrice() for latest. uint256 public whitelistPrice = 0.02 ether; uint256 public mintpassPrice = 0.04 ether; uint256 public publicPrice = 0.04 ether; // Mint limits. // @notice settable, use mintLimit() for latest. uint256 public whitelistMintLimit = 4; uint256 public mintpassMintLimit = 20; uint256 public publicMintLimit = 40; // Max tokens. uint256 public maxSupply = 10000; // Mintpassed contracts. address[] public mintpassedContracts; // Whitelist Merkle root. bytes32 public merkleRoot = 0x05ba199ba71527baf0f85acf24728a2e559447f3228c1ff56d0d90f8bb269f7d; // Constructor. constructor ( string memory _name, string memory _symbol, uint256 _tokenStartId, address[] memory _payees, uint256[] memory _shares ) PaymentSplitter(_payees, _shares) { // Deploy and set Bodies contract. bodies = new Bodies( string(abi.encodePacked(_name, ": Bodies")), // Extend name. string(abi.encodePacked(_symbol, "B")), // Extend symbol. _tokenStartId ); // Set this Project contract as parent project. bodies.setProjectAddress(address(this)); // Transfer bodies contract ownership to deployer. bodies.transferOwnership(_msgSender()); // Deploy and set Legs contract. legs = new Legs( string(abi.encodePacked(_name, ": Legs")), // Extend name. string(abi.encodePacked(_symbol, "L")), // Extend symbol. _tokenStartId ); // Set this Project contract as parent project. legs.setProjectAddress(address(this)); // Transfer legs contract ownership to deployer. legs.transferOwnership(_msgSender()); } // Mint check helper. modifier mintCheck (address _to, uint256 _numToMint) { // Early bail if paused. require(status != Status.Paused, "Minting is paused"); // Ensure sender. require(_to == _msgSender(), "Can only mint for self"); // Protect against contract minting. require(!Address.isContract(_msgSender()), "Cannot mint from contract"); // Ensure non-zero mint amount. require(_numToMint > 0, "Cannot mint zero tokens"); // Ensure available supply. require(totalSupply() + _numToMint <= maxSupply, "Max supply exceeded"); // Ensure mint limit not exceeded. require(_numToMint <= mintLimit(), "Cannot mint this many tokens"); // Ensure proper payment. require(msg.value == _numToMint * mintPrice(), "Incorrect payment amount sent"); _; } // Set mint price. function setPrice (Status _status, uint256 _newPrice) external onlyOwner { if (_status == Status.Whitelist) { whitelistPrice = _newPrice; } if (_status == Status.Mintpass) { mintpassPrice = _newPrice; } if (_status == Status.Public) { publicPrice = _newPrice; } } // Set mint limit. function setMintLimit (Status _status, uint256 _newLimit) external onlyOwner { if (_status == Status.Whitelist) { whitelistMintLimit = _newLimit; } if (_status == Status.Mintpass) { mintpassMintLimit = _newLimit; } if (_status == Status.Public) { publicMintLimit = _newLimit; } } // Set the bodies contract. function setBodies (address _newAddr) external onlyOwner { bodies = Bodies(_newAddr); } // Set the legs contract. function setLegs (address _newAddr) external onlyOwner { legs = Legs(_newAddr); } // (Re-)set the whitelist Merkle root. function setMerkleRoot (bytes32 _newRoot) external onlyOwner { merkleRoot = _newRoot; } // Set the mint status. function setStatus (Status _newStatus) external onlyOwner { // Update. status = _newStatus; // Broadcast. emit StatusChange(_newStatus); } // (Re-)set the list of Mintpassed Contracts. function setMintpassedContracts (address[] calldata _newAddrs) external onlyOwner { delete mintpassedContracts; mintpassedContracts = _newAddrs; } // Add a new Mintpassed Contract. function addMintpassedContract (address _addr) external onlyOwner { mintpassedContracts.push(_addr); } // Check if an address is whitelisted via Merkle proof validation. function isWhitelistedAddress (address _addr, bytes32[] calldata _merkleProof) public view returns (bool) { // Verify Merkle tree proof. bytes32 leaf = keccak256(abi.encodePacked(_addr)); return MerkleProof.verify(_merkleProof, merkleRoot, leaf); } // Check if an address is mintpassed (has a balance on a Mintpassed Contract). function isMintpassedAddress (address _addr) public view returns (bool) { // Cache array length to save gas. uint256 len = mintpassedContracts.length; // Loop through Mintpassed Contracts. for (uint256 i = 0; i < len; i++) { // Instantiate this Mintpassed Contract. MintpassedContract mintpassedContract = MintpassedContract(mintpassedContracts[i]); // Check if the address has a non-zero balance. if (mintpassedContract.balanceOf(_addr) > 0) { return true; } } // Not allowed. return false; } // Proxy supply to bodies. function totalSupply () public view returns (uint256) { return bodies.totalSupply(); } // Proxy balance to bodies. function balanceOf (address _owner) public view returns (uint256) { return bodies.balanceOf(_owner); } // Dynamic mint price. function mintPrice () public view returns (uint256) { // Paused. if (status == Status.Paused) { // Failsafe, but if you find a way go for it. return 1000000 ether; } // Whitelist. if (status == Status.Whitelist) { return whitelistPrice; } // Mintpass. if (status == Status.Mintpass) { return mintpassPrice; } // Public. return publicPrice; } // Dynamic mint limit. function mintLimit () public view returns (uint256) { // Paused. if (status == Status.Paused) { return 0; } // Whitelist. if (status == Status.Whitelist) { return whitelistMintLimit; } // Mintpass. if (status == Status.Mintpass) { return mintpassMintLimit; } // Public. return publicMintLimit; } // Mint. function mint (address _to, uint256 _numToMint) external payable nonReentrant mintCheck(_to, _numToMint) { // Not for whitelist mints. require(status != Status.Whitelist, "Whitelist mints must provide proof via mintWhitelist()"); // Mintpass. if (status == Status.Mintpass) { // Check eligibility. require(isMintpassedAddress(_to), "Address is not mintpassed"); } // Okay mint. _mint(_to, _numToMint); } // Mint whitelist. function mintWhitelist (address _to, uint256 _numToMint, bytes32[] calldata _merkleProof) external payable nonReentrant mintCheck(_to, _numToMint) { // Require whitelist status. require(status == Status.Whitelist, "Whitelist mints only"); // Check balance. require((balanceOf(_to) + _numToMint) <= mintLimit(), "Whitelist mint limit exceeded"); // Check whitelist eligibility. require(isWhitelistedAddress(_to, _merkleProof), "Address is not whitelisted"); // Okay mint. _mint(_to, _numToMint); } // Actually mint. function _mint (address _to, uint256 _numToMint) private { // Mint bodies & legs. bodies.mint(_to, _numToMint); legs.mint(_to, _numToMint); } } // Mintpassed Contract interface. interface MintpassedContract { function balanceOf(address _account) external view returns (uint256); } // 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 (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 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // 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 (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT /** * @title Complete the Punks: Bodies * @dev Mints Body NFTs for a parent Punk project * @author earlybail.eth | Cranky Brain Labs * @notice #GetBodied */ /* ;╟██▓▒ :╟██▓▒ ,φ▒╣╬╬╩╩Γ ╙╩╬╬╬▓▒░ ,╓φ╣▓█╬Γ ╚╣█▓╬▒╓, ,,╓╓╓╓, φ╣▓▓╬╩"" ""╚╣▓▓▒░ ]╟▓████▓▒ φφ╬╬╬╬╩╙ '╚╩╬╬╬▒▒░ φ╫███▓╬╬╬▓▒░ ]╟▓█▓▒ :╟▓█▓▒ φ╫██╬▒ ╚╣█▓╬φ,, :╟██▓▒ :╟██▓▒ φ╫██▓▒ "╙╠╣▓▓▒░ :╟██▓▒ :╟██▓▒ φφ▒▒▒▒╬╬╬╩╩' φ╫██▓▒ :╟██▓▒ ,,, :╟██▓▒ ]╟▓████▓╬⌐ φ╫██▓▒ :╟██▓▒ .╠╣▓▓▒ :╟██▓▒ :╟███╬╩"' φ╫██▓▒ :╟██▓▒ :╟██▓▒ φφ▒φ░ ,φ▒▒░ :╟██▓▒ :╟██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ '╠▓█▓▒ ╚╣█▓╬⌐:╟███▒≥, '╠▓█▓╬≥, ,,φ╣██╬░ :╟██▓▒ :╟██▓▒ ^"╙"' "╙╙" :╟█████▓▒~ ^"╙╠╣▓▓▒~ φ╣▓▓╬╩╙" :╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ╠▓██╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟███▒ ╚╟▓█╬▒╓╠▓██╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╚╣▓▓████╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬╬████╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟███▒╓, ╚╣██╬⌐ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟█████▓▒~ '"╙╙" ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ≤φ▒╬╬╬╬╚ :╟██▓▒ :╟██▓▒ :╟███▒ ╚╣██╬▒,,,,,,,φ╟▓█▓╩ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╩╬╣▓▓▓▓▓▓▓▓╬╬╚╙' :╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬▓▓▓▓▓▓▓╬╩░ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ ]φ╣▓▒░ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╠╬▓╩░ :╟██▓▒ :╟███▒, :╟██▓▒ :╟██▓▒ :╟████▓▒▒ :╟██▓▒ :╟██▓▒ ╚╬█████▓▒▒╣██▓▒ :╟██▓▒ "╠▓████████▓▒ :╟██▓▒ */ // Directives. pragma solidity 0.8.9; // Local deps. import "./Component.sol"; // Contract. contract Bodies is Component { // Constructor. constructor ( string memory _name, string memory _symbol, uint256 _tokenStartId ) Component(_name, _symbol, _tokenStartId) {} } // SPDX-License-Identifier: MIT /** * @title Complete the Punks: Legs * @dev Mints Leg NFTs for a parent Punk project * @author earlybail.eth | Cranky Brain Labs * @notice #LegsFuknGooo */ /* φ╫██▓▒ :╟██▓▒ φ╫██▓▒ ,φ▒▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒░ :╟██▓▒ φ╫██▓▒ φ╣███████████████▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓╩╙╙╙╙╙╙╙╚╣██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ "╩╬▓╬▒φφ, :╟██▓▒ ╚╬▓╬╬▒φε φ╫██▓▒ 7╟▓█▓▒, ;╟██▓▒ `╠╣█▓╬░ φ╫██▓▒ "╙╩╬╣▓▓▓▓▓███▓▒ ^╙╩╬╣▓▓▓▓▓▒░ φ╫██▓▒ ╚╠╣███████▓▒ "╠╬████╬╬▒φε φ╫██▓▒ ```╠╠███▒, ```░╠╣██╬[ φ╫████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████╬[ "╠╬███████████████████████████████████████████████╬╩ `^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ // Directives. pragma solidity 0.8.9; // Local deps. import "./Component.sol"; // Contract. contract Legs is Component { // Constructor. constructor ( string memory _name, string memory _symbol, uint256 _tokenStartId ) Component(_name, _symbol, _tokenStartId) {} } // 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) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 /** * @title Complete the Punks: Component * @dev Base component contract for Bodies + Legs * @author earlybail.eth | Cranky Brain Labs * @notice #GetBodied #LegsFuknGooo */ // Directives. pragma solidity 0.8.9; // Third-party deps. import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // Contract. contract Component is ERC721, ReentrancyGuard, Ownable { // Strings. using Strings for uint256; // Counters. using Counters for Counters.Counter; // Supply counter. Counters.Counter private _supply; // Parent Project contract address. address public projectAddress; // OpenSea Proxy contract address. address public openSeaProxyContractAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; // Base URI. string public baseURI; // Base extension. string public baseExtension = ""; // Provenance hash. string public provenanceHash; // Mint ID tracking. mapping(uint256 => uint256) private _tokenIdCache; uint256 public remainingTokenCount = 10000; // Token start ID. uint256 public tokenStartId = 0; // Constructor. constructor ( string memory _name, string memory _symbol, uint256 _tokenStartId ) ERC721(_name, _symbol) { // Set token start ID. tokenStartId = _tokenStartId; } // Only allow the project contract as caller. modifier onlyProject () { require(_msgSender() == projectAddress, "Only the parent Project contract can call this method"); _; } // Get base URI. function _baseURI () internal view virtual override returns (string memory) { return baseURI; } // Set project address. function setProjectAddress (address _newAddr) external onlyOwner { projectAddress = _newAddr; } // Set base URI. function setBaseURI (string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } // Set base extension. function setBaseExtension (string memory _newBaseExtension) external onlyOwner { baseExtension = _newBaseExtension; } // Set the token start ID. function setTokenStartId (uint256 _newId) external onlyOwner { tokenStartId = _newId; } // Set provenance hash. function setProvenanceHash (string memory _newHash) external onlyOwner { provenanceHash = _newHash; } // Set OpenSea proxy address. // Rinkeby: 0x1E525EEAF261cA41b809884CBDE9DD9E1619573A // Mainnet: 0xa5409ec958C83C3f309868babACA7c86DCB077c1 // Disable: 0x0000000000000000000000000000000000000000 function setOpenSeaProxyAddress (address _newAddress) external onlyOwner { openSeaProxyContractAddress = _newAddress; } // Token URI. function tokenURI (uint256 _tokenId) public view virtual override returns (string memory) { // Ensure existence. require(_exists(_tokenId), "Query for non-existent token"); // Cache. string memory currentBaseURI = _baseURI(); // Concatenate. return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), baseExtension)) : ""; } // Get the current total supply. function totalSupply () public view returns (uint256) { return _supply.current(); } // Mint. function mint (address _to, uint256 _numToMint) public nonReentrant onlyProject { _mintLoop(_to, _numToMint); } // Actually mint. function _mintLoop (address _to, uint256 _numToMint) private { for (uint256 i = 0; i < _numToMint; i++) { // Draw ID. uint256 tokenId = drawTokenId(); // Safe mint. _safeMint(_to, tokenId); // Increment supply counter. _supply.increment(); } } // Draw token ID. function drawTokenId () private returns (uint256) { // Generate an index. uint256 num = uint256( keccak256( abi.encode( _msgSender(), name(), symbol(), blockhash(block.number - 1), block.number, block.timestamp, block.difficulty, tx.gasprice, remainingTokenCount, projectAddress ) ) ); // Mod. uint256 index = num % remainingTokenCount; // If we haven't already drawn this index, use it directly as tokenId. // Otherwise, pull the tokenId we cached at this index last time. uint256 tokenId = _tokenIdCache[index] == 0 ? index : _tokenIdCache[index]; // Cache this index with the tail of remainingTokenCount. _tokenIdCache[index] = _tokenIdCache[remainingTokenCount - 1] == 0 ? remainingTokenCount - 1 : _tokenIdCache[remainingTokenCount - 1]; // Decrement remaining tokens. remainingTokenCount = remainingTokenCount - 1; // Return with optional start offset. return tokenId + tokenStartId; } // Public exists. function exists (uint256 _tokenId) public view returns (bool) { return _exists(_tokenId); } // Override operator approval. function isApprovedForAll (address _owner, address _operator) public override view returns (bool) { // Skip if disabled. if (openSeaProxyContractAddress != address(0)) { // Instantiate proxy registry. ProxyRegistry proxyRegistry = ProxyRegistry(openSeaProxyContractAddress); // Check proxy. if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } } // Defer. return super.isApprovedForAll(_owner, _operator); } } // Proxy. contract OwnableDelegateProxy {} // Proxy registry. contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // 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 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 (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/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Set the mint status. Update. Broadcast.
function setStatus (Status _newStatus) external onlyOwner { status = _newStatus; emit StatusChange(_newStatus); }
13,613,425
[ 1, 694, 326, 312, 474, 1267, 18, 2315, 18, 19687, 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, 445, 9433, 261, 1482, 389, 2704, 1482, 13, 3903, 1338, 5541, 288, 203, 3639, 1267, 273, 389, 2704, 1482, 31, 203, 203, 3639, 3626, 2685, 3043, 24899, 2704, 1482, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9C1dC986D786534c13Ec32eFA6C7A1631898d102/sources/inari1.sol
stake resulting crXSUSHI into BENTO for `msg.sender`
bento.deposit(IERC20(crXSushiToken), address(this), msg.sender, IERC20(crXSushiToken).balanceOf(address(this)), 0);
3,116,934
[ 1, 334, 911, 8156, 4422, 60, 6639, 2664, 45, 1368, 605, 2222, 51, 364, 1375, 3576, 18, 15330, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 324, 29565, 18, 323, 1724, 12, 45, 654, 39, 3462, 12, 3353, 60, 55, 1218, 77, 1345, 3631, 1758, 12, 2211, 3631, 1234, 18, 15330, 16, 467, 654, 39, 3462, 12, 3353, 60, 55, 1218, 77, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 374, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // GO TO LINE 1904 TO SEE WHERE THE PUMPKINS CONTRACT STARTS // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.7.0; pragma abicoder v2; contract PixelPumpkins is ERC721, Ownable { using SafeMath for uint256; string public PUMPKIN_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN PUMPKINS ARE ALL SOLD OUT string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE uint256 public constant pumpkinPrice = 40000000000000000; // 0.03 ETH uint public constant maxPumpkinPurchase = 25; uint256 public constant MAX_PUMPKINS = 8888; bool public saleIsActive = false; mapping(uint => string) public pumpkinNames; // Reserve 125 Pumpkins for team - Giveaways/Prizes etc uint public pumpkinReserve = 125; event pumpkinNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText); constructor() ERC721("Pixel Pumpkins Club", "PPC") { } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function reservePumpkins(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= pumpkinReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } pumpkinReserve = pumpkinReserve.sub(_reserveAmount); } function setProvenanceHash(string memory provenanceHash) public onlyOwner { PUMPKIN_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } // Returns the license for tokens function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A PUMPKIN WITHIN RANGE"); return LICENSE_TEXT; } // Locks the license to prevent further changes function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } // Change the license function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } function mintPixelPumpkin(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint a Pumpkin"); require(numberOfTokens > 0 && numberOfTokens <= maxPumpkinPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_PUMPKINS, "Purchase would exceed max supply of Pumpkins"); require(msg.value >= pumpkinPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_PUMPKINS) { _safeMint(msg.sender, mintIndex); } } } function changePumpkinName(uint _tokenId, string memory _name) public { require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this pumpkin!"); require(sha256(bytes(_name)) != sha256(bytes(pumpkinNames[_tokenId])), "New name is same as the current one"); pumpkinNames[_tokenId] = _name; emit pumpkinNameChange(msg.sender, _tokenId, _name); } function viewPumpkinName(uint _tokenId) public view returns( string memory ){ require( _tokenId < totalSupply(), "Choose a pumpkin within range" ); return pumpkinNames[_tokenId]; } // GET ALL PUMPKINS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH function pumpkinNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = pumpkinNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } }
GET ALL PUMPKINS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH Return an empty array
function pumpkinNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = pumpkinNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } }
5,922,447
[ 1, 3264, 8061, 453, 2799, 8784, 706, 55, 15932, 432, 30293, 15146, 5355, 8175, 14884, 15932, 9469, 55, 18, 678, 31090, 9722, 9722, 11976, 490, 5255, 5948, 11083, 24142, 14780, 2056, 432, 7128, 9749, 13601, 1599, 17, 1985, 16585, 2000, 392, 1008, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 293, 2801, 15984, 1557, 951, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 12, 1080, 8526, 3778, 262, 288, 203, 3639, 2254, 5034, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 327, 394, 533, 8526, 12, 20, 1769, 203, 5411, 533, 8526, 3778, 563, 273, 394, 533, 8526, 12, 2316, 1380, 1769, 203, 5411, 2254, 5034, 770, 31, 203, 5411, 364, 261, 1615, 273, 374, 31, 770, 411, 1147, 1380, 31, 770, 27245, 288, 203, 7734, 563, 63, 1615, 65, 273, 293, 2801, 15984, 1557, 63, 1147, 951, 5541, 21268, 24899, 8443, 16, 770, 13, 308, 274, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.6; import "./openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import "./openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "./openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "./openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "./openzeppelin-solidity/contracts/access/roles/MinterRole.sol"; import "./openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "./openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./InvictusWhitelist.sol"; /** * Contract for CRYPTO10 Hedged (C10) fund. * */ contract C10Token is ERC20, ERC20Detailed, ERC20Burnable, Ownable, Pausable, MinterRole { using SafeERC20 for ERC20; using SafeMath for uint256; // Maps participant addresses to the eth balance pending token issuance mapping(address => uint256) public pendingBuys; // The participant accounts waiting for token issuance address[] public participantAddresses; // Maps participant addresses to the withdrawal request mapping (address => uint256) public pendingWithdrawals; address payable[] public withdrawals; uint256 private minimumWei = 50 finney; uint256 private fees = 5; // 0.5% , or 5/1000 uint256 private minTokenRedemption = 1 ether; uint256 private maxAllocationsPerTx = 50; uint256 private maxWithdrawalsPerTx = 50; Price public price; address public whitelistContract; struct Price { uint256 numerator; uint256 denominator; } event PriceUpdate(uint256 numerator, uint256 denominator); event AddLiquidity(uint256 value); event RemoveLiquidity(uint256 value); event DepositReceived(address indexed participant, uint256 value); event TokensIssued(address indexed participant, uint256 amountTokens, uint256 etherAmount); event WithdrawRequest(address indexed participant, uint256 amountTokens); event Withdraw(address indexed participant, uint256 amountTokens, uint256 etherAmount); event TokensClaimed(address indexed token, uint256 balance); constructor (uint256 priceNumeratorInput, address whitelistContractInput) ERC20Detailed("Crypto10 Hedged", "C10", 18) ERC20Burnable() Pausable() public { price = Price(priceNumeratorInput, 1000); require(priceNumeratorInput > 0, "Invalid price numerator"); require(whitelistContractInput != address(0), "Invalid whitelist address"); whitelistContract = whitelistContractInput; } /** * @dev fallback function that buys tokens if the sender is whitelisted. */ function () external payable { buyTokens(msg.sender); } /** * @dev Explicitly buy via contract. */ function buy() external payable { buyTokens(msg.sender); } /** * Sets the maximum number of allocations in a single transaction. * @dev Allows us to configure batch sizes and avoid running out of gas. */ function setMaxAllocationsPerTx(uint256 newMaxAllocationsPerTx) external onlyOwner { require(newMaxAllocationsPerTx > 0, "Must be greater than 0"); maxAllocationsPerTx = newMaxAllocationsPerTx; } /** * Sets the maximum number of withdrawals in a single transaction. * @dev Allows us to configure batch sizes and avoid running out of gas. */ function setMaxWithdrawalsPerTx(uint256 newMaxWithdrawalsPerTx) external onlyOwner { require(newMaxWithdrawalsPerTx > 0, "Must be greater than 0"); maxWithdrawalsPerTx = newMaxWithdrawalsPerTx; } /// Sets the minimum wei when buying tokens. function setMinimumBuyValue(uint256 newMinimumWei) external onlyOwner { require(newMinimumWei > 0, "Minimum must be greater than 0"); minimumWei = newMinimumWei; } /// Sets the minimum number of tokens to redeem. function setMinimumTokenRedemption(uint256 newMinTokenRedemption) external onlyOwner { require(newMinTokenRedemption > 0, "Minimum must be greater than 0"); minTokenRedemption = newMinTokenRedemption; } /// Updates the price numerator. function updatePrice(uint256 newNumerator) external onlyMinter { require(newNumerator > 0, "Must be positive value"); price.numerator = newNumerator; allocateTokens(); processWithdrawals(); emit PriceUpdate(price.numerator, price.denominator); } /// Updates the price denominator. function updatePriceDenominator(uint256 newDenominator) external onlyMinter { require(newDenominator > 0, "Must be positive value"); price.denominator = newDenominator; } /** * Whitelisted token holders can request token redemption, and withdraw ETH. * @param amountTokensToWithdraw The number of tokens to withdraw. * @dev withdrawn tokens are burnt. */ function requestWithdrawal(uint256 amountTokensToWithdraw) external whenNotPaused onlyWhitelisted { address payable participant = msg.sender; require(balanceOf(participant) >= amountTokensToWithdraw, "Cannot withdraw more than balance held"); require(amountTokensToWithdraw >= minTokenRedemption, "Too few tokens"); burn(amountTokensToWithdraw); uint256 pendingAmount = pendingWithdrawals[participant]; if (pendingAmount == 0) { withdrawals.push(participant); } pendingWithdrawals[participant] = pendingAmount.add(amountTokensToWithdraw); emit WithdrawRequest(participant, amountTokensToWithdraw); } /// Allows owner to claim any ERC20 tokens. function claimTokens(ERC20 token) external payable onlyOwner { require(address(token) != address(0), "Invalid address"); uint256 balance = token.balanceOf(address(this)); token.transfer(owner(), token.balanceOf(address(this))); emit TokensClaimed(address(token), balance); } /** * @dev Allows the owner to burn a specific amount of tokens on a participant's behalf. * @param value The amount of tokens to be burned. */ function burnForParticipant(address account, uint256 value) public onlyOwner { _burn(account, value); } /** * @dev Function to mint tokens when not paused. * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter whenNotPaused returns (bool) { _mint(to, value); return true; } /// Adds liquidity to the contract, allowing anyone to deposit ETH function addLiquidity() public payable { require(msg.value > 0, "Must be positive value"); emit AddLiquidity(msg.value); } /// Removes liquidity, allowing managing wallets to transfer eth to the fund wallet. function removeLiquidity(uint256 amount) public onlyOwner { require(amount <= address(this).balance, "Insufficient balance"); msg.sender.transfer(amount); emit RemoveLiquidity(amount); } /// Allow the owner to remove a minter function removeMinter(address account) public onlyOwner { require(account != msg.sender, "Use renounceMinter"); _removeMinter(account); } /// Allow the owner to remove a pauser function removePauser(address account) public onlyOwner { require(account != msg.sender, "Use renouncePauser"); _removePauser(account); } /// returns the number of withdrawals pending. function numberWithdrawalsPending() public view returns (uint256) { return withdrawals.length; } /// returns the number of pending buys, waiting for token issuance. function numberBuysPending() public view returns (uint256) { return participantAddresses.length; } /** * First phase of the 2-part buy, the participant deposits eth and waits * for a price to be set so the tokens can be minted. * @param participant whitelisted buyer. */ function buyTokens(address participant) internal whenNotPaused onlyWhitelisted { assert(participant != address(0)); // Ensure minimum investment is met require(msg.value >= minimumWei, "Minimum wei not met"); uint256 pendingAmount = pendingBuys[participant]; if (pendingAmount == 0) { participantAddresses.push(participant); } // Increase the pending balance and wait for the price update pendingBuys[participant] = pendingAmount.add(msg.value); emit DepositReceived(participant, msg.value); } /// Internal function to allocate token. function allocateTokens() internal { uint256 numberOfAllocations = participantAddresses.length <= maxAllocationsPerTx ? participantAddresses.length : maxAllocationsPerTx; address payable ownerAddress = address(uint160(owner())); for (uint256 i = numberOfAllocations; i > 0; i--) { address participant = participantAddresses[i - 1]; uint256 deposit = pendingBuys[participant]; uint256 feeAmount = deposit.mul(fees) / 1000; uint256 balance = deposit.sub(feeAmount); uint256 newTokens = balance.mul(price.numerator) / price.denominator; pendingBuys[participant] = 0; participantAddresses.pop(); ownerAddress.transfer(feeAmount); mint(participant, newTokens); emit TokensIssued(participant, newTokens, balance); } } /// Internal function to process withdrawals. function processWithdrawals() internal { uint256 numberOfWithdrawals = withdrawals.length <= maxWithdrawalsPerTx ? withdrawals.length : maxWithdrawalsPerTx; address payable ownerAddress = address(uint160(owner())); for (uint256 i = numberOfWithdrawals; i > 0; i--) { address payable participant = withdrawals[i - 1]; uint256 tokens = pendingWithdrawals[participant]; assert(tokens > 0); // participant must have requested a withdrawal uint256 withdrawValue = tokens.mul(price.denominator) / price.numerator; pendingWithdrawals[participant] = 0; withdrawals.pop(); if (address(this).balance >= withdrawValue) { uint256 feeAmount = withdrawValue.mul(fees) / 1000; uint256 balance = withdrawValue.sub(feeAmount); participant.transfer(balance); ownerAddress.transfer(feeAmount); emit Withdraw(participant, tokens, balance); } else { mint(participant, tokens); emit Withdraw(participant, tokens, 0); // indicate a failed withdrawal } } } modifier onlyWhitelisted() { require(InvictusWhitelist(whitelistContract).isWhitelisted(msg.sender), "Must be whitelisted"); _; } }
indicate a failed withdrawal
emit Withdraw(participant, tokens, 0);
910,274
[ 1, 728, 2659, 279, 2535, 598, 9446, 287, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 3626, 3423, 9446, 12, 2680, 14265, 16, 2430, 16, 374, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import { Bytes } from "./Bytes.sol"; library ScaleCodec { // Decodes a SCALE encoded uint256 by converting bytes (bid endian) to little endian format function decodeUint256(bytes memory data) internal pure returns (uint256) { uint256 number; for (uint256 i = data.length; i > 0; i--) { number = number + uint256(uint8(data[i - 1])) * (2**(8 * (i - 1))); } return number; } // Decodes a SCALE encoded compact unsigned integer function decodeUintCompact(bytes memory data) internal pure returns (uint256 v, uint8 m) { uint8 b = readByteAtIndex(data, 0); // read the first byte uint8 mode = b & 3; // bitwise operation uint256 value; if (mode == 0) { // [0, 63] value = b >> 2; // right shift to remove mode bits } else if (mode == 1) { // [64, 16383] uint8 bb = readByteAtIndex(data, 1); // read the second byte uint64 r = bb; // convert to uint64 r <<= 6; // multiply by * 2^6 r += b >> 2; // right shift to remove mode bits value = r; } else if (mode == 2) { // [16384, 1073741823] uint8 b2 = readByteAtIndex(data, 1); // read the next 3 bytes uint8 b3 = readByteAtIndex(data, 2); uint8 b4 = readByteAtIndex(data, 3); uint32 x1 = uint32(b) | (uint32(b2) << 8); // convert to little endian uint32 x2 = x1 | (uint32(b3) << 16); uint32 x3 = x2 | (uint32(b4) << 24); x3 >>= 2; // remove the last 2 mode bits value = uint256(x3); } else if (mode == 3) { // [1073741824, 4503599627370496] uint8 l = b >> 2; // remove mode bits require( l > 32, "Not supported: number cannot be greater than 32 bytes" ); } else { revert("Code should be unreachable"); } return (value, mode); } // The biggest compact supported uint is 2 ** 536 - 1. // But the biggest value supported by this method is 2 ** 256 - 1(max of uint256) function encodeUintCompact(uint256 v) internal pure returns (bytes memory) { if ( v < 64 ) { return abi.encodePacked(uint8(v << 2)); } else if ( v < 2 ** 14 ) { return abi.encodePacked(reverse16(uint16(((v << 2) + 1)))); } else if ( v < 2 ** 30 ) { return abi.encodePacked(reverse32(uint32(((v << 2) + 2)))); } else { bytes memory valueBytes = Bytes.removeEndingZero(abi.encodePacked(reverse256(v))); uint length = valueBytes.length; uint8 prefix = uint8(((length - 4) << 2) + 3); return abi.encodePacked(prefix, valueBytes); } } // Read a byte at a specific index and return it as type uint8 function readByteAtIndex(bytes memory data, uint8 index) internal pure returns (uint8) { return uint8(data[index]); } // Sources: // * https://ethereum.stackexchange.com/questions/15350/how-to-convert-an-bytes-to-address-in-solidity/50528 // * https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel function reverse256(uint256 input) internal pure returns (uint256 v) { v = input; // swap bytes v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } function reverse128(uint128 input) internal pure returns (uint128 v) { v = input; // swap bytes v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = (v >> 64) | (v << 64); } function reverse64(uint64 input) internal pure returns (uint64 v) { v = input; // swap bytes v = ((v & 0xFF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v & 0xFFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = (v >> 32) | (v << 32); } function reverse32(uint32 input) internal pure returns (uint32 v) { v = input; // swap bytes v = ((v & 0xFF00FF00) >> 8) | ((v & 0x00FF00FF) << 8); // swap 2-byte long pairs v = (v >> 16) | (v << 16); } function reverse16(uint16 input) internal pure returns (uint16 v) { v = input; // swap bytes v = (v >> 8) | (v << 8); } function encode256(uint256 input) internal pure returns (bytes32) { return bytes32(reverse256(input)); } function encode128(uint128 input) internal pure returns (bytes16) { return bytes16(reverse128(input)); } function encode64(uint64 input) internal pure returns (bytes8) { return bytes8(reverse64(input)); } function encode32(uint32 input) internal pure returns (bytes4) { return bytes4(reverse32(input)); } function encode16(uint16 input) internal pure returns (bytes2) { return bytes2(reverse16(input)); } function encodeBytes(bytes memory input) internal pure returns (bytes memory) { return abi.encodePacked( encodeUintCompact(input.length), input ); } }
right shift to remove mode bits
value = b >> 2;
14,117,309
[ 1, 4083, 4654, 358, 1206, 1965, 4125, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 460, 273, 324, 1671, 576, 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 ]
./partial_match/1/0x4fA9616AbBbFaf2EC503ade5FA3622b3604e5232/sources/src/FloridaManCard.sol
Get the price of the pack
uint256 tokenAmount = _getFMANFromUSD(usdAmount);
2,880,280
[ 1, 967, 326, 6205, 434, 326, 2298, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 1147, 6275, 273, 389, 588, 42, 9560, 1265, 3378, 40, 12, 407, 72, 6275, 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 ]
./full_match/80001/0xC52eCe999D88a49194173d5c95d31D0EeC7cEc96/sources/project_/contracts/LockableToken.sol
locked[msg.sender][_reason].validity = locked[msg.sender][_reason].validity + (_time*86400);
function extendLock( bytes32 _reason, uint256 _time ) public override onlyOwner returns (bool) { require(tokensLocked(msg.sender, _reason) > 0, NOT_LOCKED); locked[msg.sender][_reason].validity = locked[msg.sender][_reason].validity + _time; emit Locked( msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity ); return true; }
5,689,883
[ 1, 15091, 63, 3576, 18, 15330, 6362, 67, 10579, 8009, 877, 560, 273, 8586, 63, 3576, 18, 15330, 6362, 67, 10579, 8009, 877, 560, 397, 261, 67, 957, 28, 1105, 713, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 2133, 2531, 12, 203, 3639, 1731, 1578, 389, 10579, 16, 203, 3639, 2254, 5034, 389, 957, 203, 565, 262, 1071, 3849, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 7860, 8966, 12, 3576, 18, 15330, 16, 389, 10579, 13, 405, 374, 16, 4269, 67, 6589, 2056, 1769, 203, 203, 3639, 8586, 63, 3576, 18, 15330, 6362, 67, 10579, 8009, 877, 560, 273, 203, 5411, 8586, 63, 3576, 18, 15330, 6362, 67, 10579, 8009, 877, 560, 397, 203, 5411, 389, 957, 31, 203, 203, 3639, 3626, 3488, 329, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 10579, 16, 203, 5411, 8586, 63, 3576, 18, 15330, 6362, 67, 10579, 8009, 8949, 16, 203, 5411, 8586, 63, 3576, 18, 15330, 6362, 67, 10579, 8009, 877, 560, 203, 3639, 11272, 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 ]
./full_match/5/0x85094B1936bD7287C9444FaA09dCa0B257993832/sources/_openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a fraction of the total supply. _Available since v4.3._/
abstract contract GovernorVotesQuorumFraction is GovernorVotes { using Checkpoints for Checkpoints.History; Checkpoints.History private _quorumNumeratorHistory; event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator); constructor(uint256 quorumNumeratorValue) { _updateQuorumNumerator(quorumNumeratorValue); } function quorumNumerator() public view virtual returns (uint256) { return _quorumNumeratorHistory._checkpoints.length == 0 ? _quorumNumerator : _quorumNumeratorHistory.latest(); } function quorumNumerator(uint256 blockNumber) public view virtual returns (uint256) { uint256 length = _quorumNumeratorHistory._checkpoints.length; if (length == 0) { return _quorumNumerator; } if (latest._blockNumber <= blockNumber) { return latest._value; } } function quorumNumerator(uint256 blockNumber) public view virtual returns (uint256) { uint256 length = _quorumNumeratorHistory._checkpoints.length; if (length == 0) { return _quorumNumerator; } if (latest._blockNumber <= blockNumber) { return latest._value; } } Checkpoints.Checkpoint memory latest = _quorumNumeratorHistory._checkpoints[length - 1]; function quorumNumerator(uint256 blockNumber) public view virtual returns (uint256) { uint256 length = _quorumNumeratorHistory._checkpoints.length; if (length == 0) { return _quorumNumerator; } if (latest._blockNumber <= blockNumber) { return latest._value; } } return _quorumNumeratorHistory.getAtBlock(blockNumber); function quorumDenominator() public view virtual returns (uint256) { return 100; } function quorum(uint256 blockNumber) public view virtual override returns (uint256) { return (token.getPastTotalSupply(blockNumber) * quorumNumerator(blockNumber)) / quorumDenominator(); } function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance { _updateQuorumNumerator(newQuorumNumerator); } function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { require( newQuorumNumerator <= quorumDenominator(), "GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator" ); uint256 oldQuorumNumerator = quorumNumerator(); if (oldQuorumNumerator != 0 && _quorumNumeratorHistory._checkpoints.length == 0) { _quorumNumeratorHistory._checkpoints.push( ); } emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); } function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { require( newQuorumNumerator <= quorumDenominator(), "GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator" ); uint256 oldQuorumNumerator = quorumNumerator(); if (oldQuorumNumerator != 0 && _quorumNumeratorHistory._checkpoints.length == 0) { _quorumNumeratorHistory._checkpoints.push( ); } emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); } Checkpoints.Checkpoint({_blockNumber: 0, _value: SafeCast.toUint224(oldQuorumNumerator)}) _quorumNumeratorHistory.push(newQuorumNumerator); }
1,897,342
[ 1, 3625, 434, 288, 43, 1643, 29561, 97, 364, 331, 17128, 3119, 18752, 628, 392, 288, 654, 39, 3462, 29637, 97, 1147, 471, 279, 31854, 26863, 487, 279, 8330, 434, 326, 2078, 14467, 18, 389, 5268, 3241, 331, 24, 18, 23, 6315, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 611, 1643, 29561, 29637, 31488, 13724, 353, 611, 1643, 29561, 29637, 288, 203, 565, 1450, 2073, 4139, 364, 2073, 4139, 18, 5623, 31, 203, 203, 565, 2073, 4139, 18, 5623, 3238, 389, 372, 16105, 2578, 7385, 5623, 31, 203, 203, 565, 871, 4783, 16105, 2578, 7385, 7381, 12, 11890, 5034, 1592, 31488, 2578, 7385, 16, 2254, 5034, 394, 31488, 2578, 7385, 1769, 203, 203, 203, 565, 3885, 12, 11890, 5034, 31854, 2578, 7385, 620, 13, 288, 203, 3639, 389, 2725, 31488, 2578, 7385, 12, 372, 16105, 2578, 7385, 620, 1769, 203, 565, 289, 203, 203, 565, 445, 31854, 2578, 7385, 1435, 1071, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 372, 16105, 2578, 7385, 5623, 6315, 1893, 4139, 18, 2469, 422, 374, 692, 389, 372, 16105, 2578, 7385, 294, 389, 372, 16105, 2578, 7385, 5623, 18, 13550, 5621, 203, 565, 289, 203, 203, 565, 445, 31854, 2578, 7385, 12, 11890, 5034, 1203, 1854, 13, 1071, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 769, 273, 389, 372, 16105, 2578, 7385, 5623, 6315, 1893, 4139, 18, 2469, 31, 203, 3639, 309, 261, 2469, 422, 374, 13, 288, 203, 5411, 327, 389, 372, 16105, 2578, 7385, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 13550, 6315, 2629, 1854, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 4891, 6315, 1132, 31, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 565, 445, 31854, 2578, 7385, 12, 11890, 5034, 1203, 1854, 13, 1071, 1476, 5024, 1135, 261, 2 ]
./partial_match/1/0x162dFA2502e67A6B477b91f0583cAA47a4aC0662/sources/UnidoDistribution.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 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 UnidoDistribution is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} }
3,639,363
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 1351, 22954, 9003, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 1887, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 11223, 1887, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 6275, 273, 374, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4626, 5541, 31, 203, 565, 1758, 3238, 389, 318, 77, 10717, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 377, 203, 203, 97, 203, 282, 3885, 261, 2 ]
./full_match/1/0xc1BB6B6ae3b161AB145758D34D1FbfE91a3823ae/sources/contracts/Sale.sol
* @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"); }
3,114,311
[ 1, 8650, 487, 288, 22044, 17, 1887, 17, 915, 1477, 17, 2867, 17, 3890, 17, 20294, 68, 915, 1477, 68, 6487, 1496, 14928, 279, 760, 745, 18, 389, 5268, 3241, 331, 23, 18, 23, 6315, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 445, 5788, 1477, 12, 2867, 1018, 16, 1731, 3778, 501, 13, 2713, 1476, 1135, 261, 3890, 3778, 13, 288, 203, 5411, 327, 445, 5788, 1477, 12, 3299, 16, 501, 16, 315, 1887, 30, 4587, 17, 2815, 760, 745, 2535, 8863, 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, -100 ]
pragma solidity ^0.5.0; import "./zeppelin/token/ERC777/ERC777.sol"; import "./IERC677Receiver.sol"; import "./ISideToken.sol"; contract SideToken_v1 is ISideToken, ERC777 { using Address for address; using SafeMath for uint256; address public minter; uint256 private _granularity; event Transfer(address,address,uint256,bytes); constructor(string memory _tokenName, string memory _tokenSymbol, address _minterAddr, uint256 _newGranularity) ERC777(_tokenName, _tokenSymbol, new address[](0)) public { require(_minterAddr != address(0), "SideToken: Minter address is null"); require(_newGranularity >= 1, "SideToken: Granularity must be equal or bigger than 1"); minter = _minterAddr; _granularity = _newGranularity; } modifier onlyMinter() { require(_msgSender() == minter, "SideToken: Caller is not the minter"); _; } function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external onlyMinter { _mint(_msgSender(), account, amount, userData, operatorData); } /** * @dev ERC677 transfer token with additional data if the recipient is a contact. * @param recipient The address to transfer to. * @param amount The amount to be transferred. * @param data The extra data to be passed to the receiving contract. */ function transferAndCall(address recipient, uint amount, bytes calldata data) external returns (bool success) { address from = _msgSender(); _send(from, from, recipient, amount, data, "", false); emit Transfer(from, recipient, amount, data); IERC677Receiver(recipient).onTokenTransfer(from, amount, data); return true; } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `amount` is multiple of the granularity /// @param amount The quantity that want's to be checked function requireGranularityMultiple(uint256 amount) internal view { require(amount.mod(_granularity) == 0, "SideToken: Balance is not a multiple of Granularity"); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { requireGranularityMultiple(balanceOf(from).sub(amount)); requireGranularityMultiple(balanceOf(to).add(amount)); super._move(operator, from, to, amount, userData, operatorData); } function _burn( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal { requireGranularityMultiple(balanceOf(from).sub(amount)); super._burn(operator, from, amount, data, operatorData); } function _mint( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { requireGranularityMultiple(balanceOf(account).add(amount)); super._mint(operator, account, amount, userData, operatorData); } function granularity() public view returns (uint256) { return _granularity; } }
-- Helper Functions -- */ @notice Internal function that ensures `amount` is multiple of the granularity @param amount The quantity that want's to be checked
function requireGranularityMultiple(uint256 amount) internal view { require(amount.mod(_granularity) == 0, "SideToken: Balance is not a multiple of Granularity"); }
1,848,690
[ 1, 413, 9705, 15486, 1493, 342, 225, 3186, 445, 716, 11932, 1375, 8949, 68, 353, 3229, 434, 326, 25380, 225, 3844, 1021, 10457, 716, 2545, 1807, 358, 506, 5950, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2583, 43, 27234, 8438, 12, 11890, 5034, 3844, 13, 2713, 1476, 288, 203, 3639, 2583, 12, 8949, 18, 1711, 24899, 75, 27234, 13, 422, 374, 16, 315, 8895, 1345, 30, 30918, 353, 486, 279, 3229, 434, 611, 27234, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/access/AccessControl.sol"; import "./ERC721TypedMintByLockingERC20.sol"; import "./BoxWithTimeLock.sol"; /** * @title CryptoTreasure is a typed ERC721 token able to store other tokens (ETH, ERC20, ERC721 & ERC1155) * @notice The types define the erc20 token (and the amount) to lock to mint a crypto treasure * @notice The locked erc20 tokens can be release by "destroying" the crypto treasure * @notice A destroyed crypto treasure allows to withdraw stored tokens but forbids the storing. * @notice The types define the timestamp from when it is allowed for non admin to mint a crypto treasure * @notice The types define a number of crypto treasure reserved for the admins */ contract CryptoTreasure is BoxWithTimeLock, ERC721TypedMintByLockingERC20, AccessControl { string private baseURI = "https://crypto-treasures.com/treasure-metadata/4/"; // Mapping from box id to restriction mapping(uint256 => bool) public _storeRestrictedToOwnerAndApproval; // Mapping from type id to blocked destruction duration mapping(uint256 => uint256) public _lockedDestructionDuration; // Mapping from type id to minting start timestamp mapping(uint256 => uint256) public _mintStartTimestamp; // Mapping from type id to last id not reserved to admin mapping(uint256 => uint256) public _lastIdNotReserved; // Mapping from box id to destroy unlock timestamp mapping(uint256 => uint256) public _lockedDestructionEnd; /** * @dev Constructor * @notice add msg.sender as DEFAULT_ADMIN_ROLE * @param _baseBoxAddress boxBase address */ constructor(address _baseBoxAddress) ERC721TypedMintByLockingERC20("CryptoTreasures", "CTR") BoxWithTimeLock(_baseBoxAddress) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Mint crypto treasure from its id * @notice This will transferFrom() erc20 token to lock to the contract * @notice Allowance of the erc20 to lock must be done before * @notice Throw if the minting start is not yet passed * @notice Throw if the crypto treasure is reserved to an admin * * @param to address of reception * @param boxId id of the box * @param data array bytes containing: * - the type id (in first 32 bytes) * - the storing restriction (in following 8 bytes) - 1 only owner can store, 0 everyone can store */ function safeMint( address to, uint256 boxId, bytes memory data ) external nonReentrant { super._safeMint(to, boxId, data); uint256 typeId = _tokenTypes[boxId]; require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) || boxId <= _lastIdNotReserved[typeId], "e22" ); require(_mintStartTimestamp[typeId] <= block.timestamp, "e19"); _storeRestrictedToOwnerAndApproval[boxId] = Bytes._bytesToUint8(data, 32) == 1; uint256 destroyLockDuration = _lockedDestructionDuration[typeId]; if (destroyLockDuration != 0) { _lockedDestructionEnd[boxId] = block.timestamp + destroyLockDuration; } } /** * @dev Mint a crypto treasure from a type id * @notice This will transferFrom() tokens to the contract * @notice Allowance of the erc20 to lock must be done before * @notice Throw if the minting start is not yet passed * @notice Throw if there is no more crypto treasure available for this type * * @param to address of reception * @param typeId id of the type * @param data array bytes containing the storing restriction (in first 8 bytes) - 1 only owner can store, 0 everyone can store * * @return minted crypto treasure id */ function safeMintByType( address to, uint256 typeId, bytes memory data ) external nonReentrant returns (uint256) { require(_mintStartTimestamp[typeId] <= block.timestamp, "e19"); // mint the token uint256 tokenId = _safeMintByType(to, typeId, data); require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) || tokenId <= _lastIdNotReserved[typeId], "e22" ); _storeRestrictedToOwnerAndApproval[tokenId] = Bytes._bytesToUint8(data, 0) == 1; uint256 destroyLockDuration = _lockedDestructionDuration[typeId]; if (destroyLockDuration != 0) { _lockedDestructionEnd[tokenId] = block.timestamp + destroyLockDuration; } // return the token id return tokenId; } /** * @dev Mint a batch of crypto treasures from a type id * @notice only admins cal execute this function * @notice This will transferFrom() tokens to the contract * @notice Allowance of the erc20 to lock must be done before * @notice Minting can be done before the minting start for everyone * @notice Throw if there is no more crypto treasure available for this type * * @param to addresses of reception * @param typeId id of the type * @param data array bytes containing the storing restriction (in first 8 bytes) - 1 only owner can store, 0 everyone can store * * @return tokensMinted minted crypto treasure id list */ function safeBatchMintByType( address[] calldata to, uint256 typeId, bytes memory data ) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) returns (uint256[] memory tokensMinted) { // mint the tokens tokensMinted = super._safeBatchMintByType(to, typeId, data); uint256 destroyLockDuration = _lockedDestructionDuration[typeId]; // define the restriction mode for (uint256 j = 0; j < to.length; j++) { _storeRestrictedToOwnerAndApproval[tokensMinted[j]] = Bytes._bytesToUint8(data, 0) == 1; if (destroyLockDuration != 0) { _lockedDestructionEnd[tokensMinted[j]] = block.timestamp + destroyLockDuration; } } } /** * @dev lock a crypto treasure until a timestamp * @notice Only owner or approved can execute this * @notice Throw if the crypto treasure is already locked * * @param boxId id of the box * @param unlockTimestamp unlock timestamp */ function lockBox(uint256 boxId, uint256 unlockTimestamp) external { require(_isApprovedOrOwner(_msgSender(), boxId), "e4"); onlyNotLockedBox(boxId); _lockBox(boxId, unlockTimestamp); } /** * @dev Set the restriction mode of the storing * @notice Only owner or approved can execute this * @notice Throw if the crypto treasure is already locked * * @param boxId id of the box * @param restriction true: only owner can store, false: everyone can store */ function setStoreRestrictionToOwnerAndApproval( uint256 boxId, bool restriction ) external { require(_isApprovedOrOwner(_msgSender(), boxId), "e4"); onlyNotLockedBox(boxId); _storeRestrictedToOwnerAndApproval[boxId] = restriction; } /** * @dev Add one type with a range of token id * @notice Only admin can execute this function * @notice Throw if the number reserved is bigger than the range * * @param id new id type * @param from first id for this type * @param to last id for this type * @param data array bytes containing: * - the erc20 addres to lock (in first 20 bytes) * - the amount to lock (in following 32 bytes) * - the duration before destroy() is allowed after minting (in following 32 bytes) * - the duration before mint() is allowed for everyone (in following 32 bytes) * - the number of tokens reserved to admins (in following 32 bytes) */ function addType( uint256 id, uint256 from, uint256 to, bytes calldata data ) public onlyRole(DEFAULT_ADMIN_ROLE) { _addType(id, from, to, data); _lockedDestructionDuration[id] = Bytes._bytesToUint256(data, 52); _mintStartTimestamp[id] = block.timestamp + Bytes._bytesToUint256(data, 84); uint256 numberToReserved = Bytes._bytesToUint256(data, 116); require(numberToReserved <= to - from + 1, "e21"); _lastIdNotReserved[id] = to - numberToReserved; } /** * @dev Add a list of types * @notice Only admin can execute this function * * @param ids new ids * @param from first id for each type * @param to last id for each type * @param data array bytes containing: see addType() */ function addTypes( uint256[] calldata ids, uint256[] calldata from, uint256[] calldata to, bytes[] calldata data ) external onlyRole(DEFAULT_ADMIN_ROLE) { for (uint256 i = 0; i < ids.length; i++) { addType(ids[i], from[i], to[i], data[i]); } } /** * @dev Updates the base URI * @notice Only admin can execute this function * * @param _newBaseURI new base URI */ function updateBaseURI(string calldata _newBaseURI) external onlyRole(DEFAULT_ADMIN_ROLE) { baseURI = _newBaseURI; } /** * @dev Executed before a withdraw * @notice Throw if box is locked (from BoxWithTimeLock) * @notice Throw if not owner or approved * * @param boxId id of the box */ function _beforeWithdraw(uint256 boxId) internal override { super._beforeWithdraw(boxId); // Useless as the balance will be computed in the withdraw // require(_exists(boxId), "e15"); require(_isApprovedOrOwner(_msgSender(), boxId), "e4"); } /** * @dev Executed before a store * @notice Throw if box is locked (from BoxWithTimeLock) * @notice Throw if crypto treasure does not exist * @notice Throw if not approved AND if store restriction is true * @notice Throw if crypto treasure has been destroyed (from BoxExternal) * * @param boxId id of the box */ function _beforeStore(uint256 boxId) internal override { super._beforeStore(boxId); require(_exists(boxId), "e15"); require( !_storeRestrictedToOwnerAndApproval[boxId] || _isApprovedOrOwner(_msgSender(), boxId), "e7" ); } /** * @dev Executed before a destroy * @notice Throw if box is locked (from BoxWithTimeLock) * @notice Throw if not approved * @notice Throw if crypto treasure has been destroyed (from BoxExternal) * @notice Throw if before destroy allowed timestamp * * @param boxId id of the box */ function _beforeDestroy(uint256 boxId) internal override { super._beforeDestroy(boxId); require(_isApprovedOrOwner(_msgSender(), boxId), "e4"); require(_isDestructionUnlocked(boxId), "e17"); } /** * @dev Executed after a destroy * @notice Release the erc20 locked to the owner * * @param boxId id of the box */ function _afterDestroy(uint256 boxId) internal override { _unlockMint(boxId); } /** * @dev Check if the crypto treasure passed the destroy lock * * @param boxId id of the box * @return true if the crypto treasure passed the destroy lock, false otherwise */ function _isDestructionUnlocked(uint256 boxId) internal view returns (bool) { return _lockedDestructionEnd[boxId] <= block.timestamp; } function supportsInterface(bytes4 interfaceId) public view override(ERC721, AccessControl, IERC165) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Base URI for computing {tokenURI} * @return string baseURI */ function _baseURI() internal view override returns (string memory) { return baseURI; } }
* @dev Executed before a store @notice Throw if box is locked (from BoxWithTimeLock) @notice Throw if crypto treasure does not exist @notice Throw if not approved AND if store restriction is true @notice Throw if crypto treasure has been destroyed (from BoxExternal) @param boxId id of the box/
function _beforeStore(uint256 boxId) internal override { super._beforeStore(boxId); require(_exists(boxId), "e15"); require( !_storeRestrictedToOwnerAndApproval[boxId] || _isApprovedOrOwner(_msgSender(), boxId), "e7" ); }
6,486,636
[ 1, 23839, 1865, 279, 1707, 225, 3743, 309, 3919, 353, 8586, 261, 2080, 8549, 1190, 950, 2531, 13, 225, 3743, 309, 8170, 9787, 3619, 1552, 486, 1005, 225, 3743, 309, 486, 20412, 4116, 309, 1707, 9318, 353, 638, 225, 3743, 309, 8170, 9787, 3619, 711, 2118, 17689, 261, 2080, 8549, 6841, 13, 225, 3919, 548, 612, 434, 326, 3919, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 2257, 12, 11890, 5034, 3919, 548, 13, 2713, 3849, 288, 203, 3639, 2240, 6315, 5771, 2257, 12, 2147, 548, 1769, 203, 3639, 2583, 24899, 1808, 12, 2147, 548, 3631, 315, 73, 3600, 8863, 203, 3639, 2583, 12, 203, 5411, 401, 67, 2233, 18784, 774, 5541, 1876, 23461, 63, 2147, 548, 65, 747, 203, 7734, 389, 291, 31639, 1162, 5541, 24899, 3576, 12021, 9334, 3919, 548, 3631, 203, 5411, 315, 73, 27, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma ton-solidity >=0.43.0; pragma AbiHeader expire; pragma AbiHeader time; pragma AbiHeader pubkey; import "../Debot.sol"; import "IMultisig.sol"; import "https://raw.githubusercontent.com/tonlabs/DeBot-IS-consortium/main/SigningBoxInput/SigningBoxInput.sol"; import "https://raw.githubusercontent.com/tonlabs/DeBot-IS-consortium/main/Menu/Menu.sol"; import "https://raw.githubusercontent.com/tonlabs/DeBot-IS-consortium/main/ConfirmInput/ConfirmInput.sol"; import "https://raw.githubusercontent.com/tonlabs/DeBot-IS-consortium/main/Terminal/Terminal.sol"; import "IAccManCallbacks.sol"; import "../Sdk.sol"; import "InviteRoot.sol"; import "AccBase.sol"; import "../Upgradable.sol"; import "IAccManCallbacks.sol"; contract AccMan is Debot, Upgradable { uint128 constant DEPLOY_ROOT_FEE = 1 ton; uint128 constant DEPLOY_ACCOUNT_FEE = 1 ton; uint128 constant DEPLOY_INVITE_FEE = 0.3 ton; struct MultisigArgs { address dest; uint128 value; TvmCell payload; } bytes m_icon; // StateInit TvmCell m_accountBaseImage; TvmCell m_inviteImage; TvmCell m_inviteRootImage; // invoke arguments address m_invoker; TvmCell m_accountImage; uint256 m_ownerKey; address m_wallet; TvmCell m_args; uint32 m_sbHandle; uint16 m_currentSeqno; address m_account; string m_nonce; mapping(uint256 => bool) m_ownerKeys; MultisigArgs m_callArgs; optional(uint256, bool) m_currOwner; // helper vars uint32 m_gotoId; uint32 m_continue; Invoke m_invokeType; uint8 m_deployFlags; enum Invoke { NewAccount, NewPublicInvite, NewPrivateInvite, QueryAccounts, QueryPublicInvites, QueryPrivateInvites } modifier onlyOwner() { require(msg.pubkey() == tvm.pubkey(), 100); tvm.accept(); _; } function setIcon(bytes icon) public onlyOwner { m_icon = icon; } function setAccountBase(TvmCell image) public onlyOwner { m_accountBaseImage = image; } function setInvite(TvmCell image) public onlyOwner { m_inviteImage = image; } function setInviteRoot(TvmCell image) public onlyOwner { m_inviteRootImage = image; } /// @notice Entry point function for DeBot. function start() public override { } /// @notice Returns Metadata about DeBot. function getDebotInfo() public functionID(0xDEB) override view returns( string name, string version, string publisher, string caption, string author, address support, string hello, string language, string dabi, bytes icon ) { name = "Account Manager"; version = "0.2.0"; publisher = "TON Labs"; caption = "Managing user accounts"; author = "TON Labs"; support = address.makeAddrStd(0, 0x841288ed3b55d9cdafa806807f02a0ae0c169aa5edfe88a789a6482429756a94); hello = "Hello, I am an Account Manager DeBot."; language = "en"; dabi = m_debotAbi.get(); icon = m_icon; } function getRequiredInterfaces() public view override returns (uint256[] interfaces) { return [ Menu.ID, SigningBoxInput.ID ]; } // // API functions // /// @notice API function. function invokeDeployAccount( TvmCell image, uint256 deployerKey, uint256[] ownerKeys, address wallet, uint32 sbHandle, TvmCell args ) public { m_deployFlags = 0; m_invokeType = Invoke.NewAccount; m_invoker = msg.sender; if (image.toSlice().empty()) { returnOnError(Status.EmptyAccount); return; } if (deployerKey == 0) { returnOnError(Status.ZeroKey); return; } if (sbHandle == 0) { returnOnError(Status.InvalidSigningBoxHandle); return; } delete m_ownerKeys; for (uint256 key: ownerKeys) { if (key != deployerKey && key != 0) { m_ownerKeys[key] = false; } } m_ownerKey = deployerKey; m_accountImage = image; m_wallet = wallet; m_args = args; m_sbHandle = sbHandle; calcSeqno(); } /// @notice API function. function invokeQueryAccounts(uint256 ownerKey) public { m_invokeType = Invoke.QueryAccounts; m_invoker = msg.sender; m_ownerKey = ownerKey; Sdk.getAccountsDataByHash( tvm.functionId(setInvites), tvm.hash(buildInviteCode(InviteType.Self, _calcRoot())), address.makeAddrStd(-1, 0) ); } /// @notice API function. function invokeCreatePublicInvite( uint256 userKey, address account, address wallet, uint32 sbHandle ) public { m_deployFlags = 0; m_invokeType = Invoke.NewPublicInvite; m_invoker = msg.sender; if (sbHandle == 0) { return returnOnError(Status.InvalidSigningBoxHandle); } m_ownerKey = userKey; m_sbHandle = sbHandle; m_wallet = wallet; m_account = account; m_continue = tvm.functionId(createPubInvite); _checkWallet(); } /// @notice API function. function invokeCreatePrivateInvite( uint256 userKey, address account, string nonce, address wallet, uint32 sbHandle ) public { m_deployFlags = 0; m_invokeType = Invoke.NewPrivateInvite; m_invoker = msg.sender; if (sbHandle == 0) { return returnOnError(Status.InvalidSigningBoxHandle); } m_ownerKey = userKey; m_sbHandle = sbHandle; m_wallet = wallet; m_account = account; m_nonce = nonce; m_continue = tvm.functionId(createPrivInvite); _checkWallet(); } /// @notice API function. function invokeQueryPublicInvites(uint256 userKey) public { m_invokeType = Invoke.QueryPublicInvites; m_invoker = msg.sender; m_ownerKey = userKey; Sdk.getAccountsDataByHash( tvm.functionId(setAllPublicInvitesForUser), tvm.hash(buildInviteCode(InviteType.Public, _calcRoot())), address.makeAddrStd(-1, 0) ); } /// @notice API function. function invokeQueryPrivateInvites(uint256 userKey) public { m_invokeType = Invoke.QueryPrivateInvites; m_invoker = msg.sender; m_ownerKey = userKey; Sdk.getAccountsDataByHash( tvm.functionId(setAllPrivateInvitesForUser), tvm.hash(buildInviteCode(InviteType.Private, _calcRoot())), address.makeAddrStd(-1, 0) ); } /* TODO: implement add/remove nonces /// @notice API function. function invokeAddInvites( uint256 ownerKey, uint32 sbRootHandle, uint256[] nonceHashes ) public { } /// @notice API function. function invokeRemoveInvites() public { } */ ///////////////////////////////////////////////////////////////////////////////////////////////// function createPrivInvite() public { // TODO: check that nonce is valid; m_deployFlags |= CREATE_INVITE; TvmCell body = tvm.encodeBody(AccMan.deployInvite, m_ownerKey, InviteType.Private, m_account, m_nonce, m_deployFlags); this.callMultisig(address(this), body, _calcFee(m_deployFlags, 1), tvm.functionId(completePrivInvite)); } function createPubInvite() public { m_deployFlags |= CREATE_INVITE; TvmCell body = tvm.encodeBody(AccMan.deployInvite, m_ownerKey, InviteType.Public, m_account, "", m_deployFlags); this.callMultisig(address(this), body, _calcFee(m_deployFlags, 1), tvm.functionId(completePubInvite)); } function completePrivInvite() public view { IonCreatePrivateInvite(m_invoker).onCreatePrivateInvite(Status.Success); } function completePubInvite() public view { IonCreatePublicInvite(m_invoker).onCreatePublicInvite(Status.Success); } function setAllPublicInvitesForUser(AccData[] accounts) public view { address[] addrs; for (uint i = 0; i < accounts.length; i++) { addrs.push(_decodeAccountAddress(accounts[i].data)); } IonQueryPublicInvites(m_invoker).onQueryPublicInvites(addrs); } function setAllPrivateInvitesForUser(AccData[] accounts) public view { address[] addrs; for (uint i = 0; i < accounts.length; i++) { addrs.push(_decodeAccountAddress(accounts[i].data)); } IonQueryPrivateInvites(m_invoker).onQueryPrivateInvites(addrs); } function setInvites(AccData[] accounts) public view { address[] addrs; for (uint i = 0; i < accounts.length; i++) { addrs.push(_decodeAccountAddress(accounts[i].data)); } IonQueryAccounts(m_invoker).onQueryAccounts(addrs); } function checkRoot() public { address rootAddr = _calcRoot(); Sdk.getAccountType(tvm.functionId(checkRootState), rootAddr); } function menuCheckRoot(uint32 index) public { index; checkRoot(); } function checkRootState(int8 acc_type) public { if (acc_type != 1) { if (acc_type == 2) { // frozen account returnOnError(Status.RootFrozen); return; } m_deployFlags |= CREATE_ROOT; Terminal.print(0, "User Invite Root is inactive."); } else { Terminal.print(0, format("Invite Root is active: {}.", _calcRoot())); } m_currOwner = m_ownerKeys.min(); this.checkCurrentOwnerRoot(); } function checkCurrentOwnerRoot() public { if (m_currOwner.hasValue()) { (uint256 key, ) = m_currOwner.get(); Sdk.getAccountType(tvm.functionId(setCurrentRootState), _calcRootByKey(key)); } else { Terminal.print(m_continue, ""); } } function setCurrentRootState(int8 acc_type) public { if (!m_currOwner.hasValue()) { Terminal.print(m_continue, ""); return; } (uint256 key, ) = m_currOwner.get(); if (acc_type == 1) { m_ownerKeys[key] = true; } m_currOwner = m_ownerKeys.next(key); this.checkCurrentOwnerRoot(); } function signAccountCode() public { Sdk.signHash(tvm.functionId(setSignature), m_sbHandle, tvm.hash(m_accountImage.toSlice().loadRef())); } function onRootError(uint32 sdkError, uint32 exitCode) public { // TODO: handle errors Terminal.print(0, format("[DEBUG] Error: sdk code = {}, exit code = {}", sdkError, exitCode)); returnOnError(Status.RootFailed); } function setSignature(bytes signature) public { m_deployFlags |= CREATE_ACC | CREATE_INVITE; uint128 ownerCount = 1; uint128 totalFee = 0; for ((uint256 k, bool isActiveRoot): m_ownerKeys) { ownerCount++; if (!isActiveRoot) { totalFee += _calcFee(CREATE_ROOT, 0); } } totalFee += _calcFee(m_deployFlags, ownerCount); TvmCell body = tvm.encodeBody( AccMan.deployAccount, m_ownerKey, m_ownerKeys, m_currentSeqno, m_accountImage.toSlice().loadRef(), signature, m_args, m_deployFlags ); this.callMultisig(address(this), body, totalFee, tvm.functionId(checkAccount)); } function checkAccount() public { address account = address(tvm.hash(buildAccount(m_ownerKey, m_currentSeqno))); Sdk.getAccountCodeHash(tvm.functionId(checkHash), account); } function menuCheckAccount(uint32 index) public { index; checkAccount(); } function checkHash(uint256 code_hash) public { TvmCell accImage = buildAccount(m_ownerKey, m_currentSeqno); address addr = address(tvm.hash(accImage)); if (code_hash == tvm.hash(accImage.toSlice().loadRef()) || code_hash == 0) { returnOnError(Status.AccountUpdateFailed); return; } this.reportSuccess(); } function reportSuccess() public { returnOnDeployStatus(Status.Success, address(tvm.hash(buildAccount(m_ownerKey, m_currentSeqno)))); } function calcSeqno() private { m_currentSeqno = 0; Sdk.getAccountsDataByHash( tvm.functionId(setResult), tvm.hash(buildInviteCode(InviteType.Self, _calcRoot())), address.makeAddrStd(-1, 0) ); } function callMultisig(address dest, TvmCell payload, uint128 value, uint32 gotoId) public { Sdk.getBalance(tvm.functionId(callMultisig2), m_wallet); m_gotoId = gotoId; m_callArgs = MultisigArgs(dest, value, payload); } function callMultisig2(uint128 nanotokens) public { if (m_callArgs.value + 0.1 ton >= nanotokens) { return returnOnError(Status.LowWalletBalance); } optional(uint256) pubkey = m_ownerKey; optional(uint32) sbhandle = m_sbHandle; // TODO: allow transfer only from multisig with 1 custodian. IMultisig(m_wallet).sendTransaction{ abiVer: 2, extMsg: true, sign: true, pubkey: pubkey, time: 0, expire: 0, signBoxHandle: sbhandle, callbackId: tvm.functionId(onSuccess), onErrorId: tvm.functionId(onError) }(m_callArgs.dest, m_callArgs.value, true, 3, m_callArgs.payload); delete m_callArgs; } function onSuccess() public view { if (m_gotoId == tvm.functionId(checkRoot)) { this.checkRoot(); } else if (m_gotoId == tvm.functionId(checkAccount)) { this.checkAccount(); } else if (m_gotoId == tvm.functionId(completePubInvite)) { this.completePubInvite(); } else if (m_gotoId == tvm.functionId(reportSuccess)) { this.reportSuccess(); } } function onError(uint32 sdkError, uint32 exitCode) public { // TODO: handle errors Terminal.print(0, format("Error: sdk code = {}, exit code = {}", sdkError, exitCode)); returnOnError(Status.MultisigFailed); } function setResult(AccData[] accounts) public { uint16 counter = 0; for (uint i = 0; i < accounts.length; i++) { uint256 pubkey = accounts[i].data.toSlice().decode(uint256); if (pubkey == m_ownerKey) { counter++; } } m_currentSeqno = counter; m_continue = tvm.functionId(signAccountCode); _checkWallet(); } // // Checkers // function _checkWallet() private { Sdk.getBalance(tvm.functionId(checkWalletBalance), m_wallet); } function checkWalletBalance(uint128 nanotokens) public { if (nanotokens < 3 ton) { return returnOnError(Status.LowWalletBalance); } Sdk.getAccountType(tvm.functionId(checkWalletType), m_wallet); } function checkWalletType(int8 acc_type) public view { if (acc_type != 1) { return returnOnError(Status.InactiveWallet); } this.checkRoot(); } // // Helpers // function _calcRoot() private view returns (address) { return _calcRootByKey(m_ownerKey); } function _calcRootByKey(uint256 key) private view returns (address) { TvmCell rootImage = tvm.insertPubkey(m_inviteRootImage, key); return address(tvm.hash(rootImage)); } function returnOnDeployStatus(Status status, address addr) internal view { IAccManCallbacks(m_invoker).onAccountDeploy(status, addr); } function returnOnError(Status status) internal view { if (m_invokeType == Invoke.NewAccount) { returnOnDeployStatus(status, address(0)); } else if (m_invokeType == Invoke.NewPublicInvite) { IonCreatePublicInvite(m_invoker).onCreatePublicInvite(status); } else if (m_invokeType == Invoke.NewPrivateInvite) { IonCreatePrivateInvite(m_invoker).onCreatePrivateInvite(status); } } function buildAccount(uint256 ownerKey, uint16 seqno) private view returns (TvmCell image) { TvmCell code = m_accountBaseImage.toSlice().loadRef(); TvmCell newImage = tvm.buildStateInit({ code: code, pubkey: ownerKey, varInit: { seqno: seqno }, contr: AccBase }); image = newImage; } function buildInviteCode(InviteType inviteType, address inviteRoot) private view returns (TvmCell) { TvmBuilder saltBuilder; // uint8 (invite type) + address (invite root addr). saltBuilder.store(uint8(inviteType), inviteRoot); TvmCell code = tvm.setCodeSalt( m_inviteImage.toSlice().loadRef(), saltBuilder.toCell() ); return code; } function _decodeAccountAddress(TvmCell data) internal pure returns (address) { // decode invite contract data manually: // pubkey, timestamp, ctor flag, address (, , , address acc) = data.toSlice().decode(uint256, uint64, bool, address); return acc; } // // Onchain functions // uint8 constant CREATE_ACC = 1; uint8 constant CREATE_ROOT = 2; uint8 constant CREATE_INVITE = 4; function _calcFee(uint8 flags, uint128 inviteCount) private pure returns (uint128) { uint128 totalFee = (flags & CREATE_ACC) != 0 ? DEPLOY_ACCOUNT_FEE : 0; if (flags & CREATE_ROOT != 0) { totalFee += DEPLOY_ROOT_FEE; } if (flags & CREATE_INVITE != 0) { totalFee += DEPLOY_INVITE_FEE * inviteCount; } return totalFee; } function deployAccount( uint256 deployerKey, mapping(uint256 => bool) ownerKeys, uint16 seqno, TvmCell code, bytes signature, TvmCell args, uint8 flags ) public view { uint128 inviteCount = 1; uint128 totalFee = 0; for ((uint256 k, bool isActiveRoot): ownerKeys) { inviteCount++; if (!isActiveRoot) { totalFee += _calcFee(CREATE_ROOT, 0); } } totalFee += _calcFee(flags, inviteCount); require(msg.value >= totalFee, 102); if (flags & CREATE_ROOT != 0) { deployInviteRoot(deployerKey); } if (flags & CREATE_ACC != 0) { require(tvm.checkSign(tvm.hash(code), signature.toSlice(), deployerKey), 103); TvmCell state = buildAccount(deployerKey, seqno); address account = new AccBase{value: DEPLOY_ACCOUNT_FEE - 0.1 ton, flag: 1, bounce: true, stateInit: state}(); AccBase(account).upgrade{value: 0.1 ton, flag: 1, bounce: true}(code, signature, args); if (flags & CREATE_INVITE != 0) { deployInvite(deployerKey, InviteType.Self, account, "", 0); for ((uint256 key, bool isActiveRoot): ownerKeys) { deployInvite(key, InviteType.Public, account, "", !isActiveRoot ? CREATE_ROOT : 0); } // TODO: support private invites } } } function deployInvite( uint256 ownerKey, InviteType invType, address account, string nonce, uint8 flags ) public view { uint128 fee = _calcFee(flags | CREATE_INVITE, 1); require(msg.value >= fee, 102); if (flags & CREATE_ROOT != 0) { deployInviteRoot(ownerKey); } TvmCell rootImage = tvm.insertPubkey(m_inviteRootImage, ownerKey); address root = address(tvm.hash(rootImage)); if (invType == InviteType.Public) { InviteRoot(root).createPublicInvite{ value: DEPLOY_INVITE_FEE - 0.01 ton, flag: 0, bounce: true }(account); } else if (invType == InviteType.Private) { InviteRoot(root).createPrivateInvite{ value: DEPLOY_INVITE_FEE - 0.01 ton, flag: 0, bounce: true }(nonce, account); } else if (invType == InviteType.Self) { InviteRoot(root).createSelfInvite{ value: DEPLOY_INVITE_FEE - 0.01 ton, flag: 0, bounce: true }(account); } } function deployInviteRoot(uint256 ownerKey) public view { uint128 fee = _calcFee(CREATE_ROOT, 0); require(msg.value >= fee, 102); TvmCell state = tvm.insertPubkey(m_inviteRootImage, ownerKey); new InviteRoot {value: fee - 0.01 ton, flag: 1, stateInit: state}(m_inviteImage, address(this)); } // // Get-methods // // // Upgradable Impl // function onCodeUpgrade() internal override { } }
@notice Entry point function for DeBot.
function start() public override { }
7,282,350
[ 1, 1622, 1634, 445, 364, 1505, 6522, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 787, 1435, 1071, 3849, 288, 203, 540, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xacf1FD71B160cc82446dB9F213B94495Ee70Af30/sources/BlackJesus.sol
@custom:security-contact [email protected]
contract BlackJesus is ERC20, Ownable { pragma solidity ^0.8.9; constructor() ERC20("Black Jesus", "BJESUS") { _mint(msg.sender, 777777777777777 * 10 ** decimals()); } }
4,195,211
[ 1, 36, 3662, 30, 7462, 17, 8994, 1123, 36, 11223, 78, 281, 407, 18, 10256, 73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 22467, 46, 281, 407, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 13155, 804, 281, 407, 3113, 315, 38, 46, 3991, 3378, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2371, 4700, 4700, 4700, 4700, 4700, 4700, 4700, 380, 1728, 2826, 15105, 10663, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x7F22e1B9102595DcBeF8D041855fbA11c2485168/sources/https_/github.com/abdk-consulting/abdk-libraries-solidity/blob/v3.0/ABDKMathQuad.sol
We rely on overflow behavior here
unchecked { if (x == 0) return bytes16 (0); else { uint256 result = uint256 (x > 0 ? x : -x); uint256 msb = mostSignificantBit (result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16255 + msb << 112; if (x < 0) result |= 0x80000000000000000000000000000000; return bytes16 (uint128 (result)); } }
1,885,793
[ 1, 3218, 21187, 603, 9391, 6885, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 22893, 288, 203, 1377, 309, 261, 92, 422, 374, 13, 327, 1731, 2313, 261, 20, 1769, 203, 1377, 469, 288, 203, 3639, 2254, 5034, 563, 273, 2254, 5034, 261, 92, 405, 374, 692, 619, 294, 300, 92, 1769, 203, 203, 3639, 2254, 5034, 4086, 70, 273, 4486, 29822, 5775, 261, 2088, 1769, 203, 3639, 309, 261, 959, 70, 411, 23543, 13, 563, 22789, 23543, 300, 4086, 70, 31, 203, 3639, 469, 309, 261, 959, 70, 405, 23543, 13, 563, 23359, 4086, 70, 300, 23543, 31, 203, 203, 3639, 563, 273, 563, 473, 374, 6356, 8998, 8998, 8998, 8998, 8998, 18343, 571, 2872, 10395, 397, 4086, 70, 2296, 23543, 31, 203, 3639, 309, 261, 92, 411, 374, 13, 563, 5626, 374, 92, 28, 12648, 12648, 12648, 17877, 31, 203, 203, 3639, 327, 1731, 2313, 261, 11890, 10392, 261, 2088, 10019, 203, 1377, 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 ]
./partial_match/1/0x7F346F1eB7a65fF83f51B3FD76dCc70979e6DF38/sources/@arrakisfi/v3-lib-0.8/contracts/SqrtPriceMath.sol
@title Functions based on Q64.96 sqrt price and liquidity @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath { using SafeCast for uint256; function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp pragma solidity >=0.8.0; ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } }
2,715,586
[ 1, 7503, 2511, 603, 2238, 1105, 18, 10525, 5700, 6205, 471, 4501, 372, 24237, 225, 8398, 326, 4233, 716, 4692, 8576, 1365, 434, 6205, 487, 279, 2238, 1105, 18, 10525, 471, 4501, 372, 24237, 358, 3671, 20113, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 348, 85, 3797, 5147, 10477, 288, 203, 565, 1450, 14060, 9735, 364, 2254, 5034, 31, 203, 203, 565, 445, 24418, 20, 9242, 12, 203, 3639, 2254, 16874, 5700, 8541, 2501, 10525, 16, 203, 3639, 2254, 16874, 5700, 8541, 38, 60, 10525, 16, 203, 3639, 2254, 10392, 4501, 372, 24237, 16, 203, 3639, 1426, 3643, 1211, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 3844, 20, 13, 288, 203, 3639, 309, 261, 24492, 8541, 2501, 10525, 405, 5700, 8541, 38, 60, 10525, 13, 261, 24492, 8541, 2501, 10525, 16, 5700, 8541, 38, 60, 10525, 13, 273, 261, 24492, 8541, 38, 60, 10525, 16, 5700, 8541, 2501, 10525, 1769, 203, 203, 3639, 2254, 5034, 16730, 21, 273, 2254, 5034, 12, 549, 372, 24237, 13, 2296, 15038, 2148, 10525, 18, 17978, 13269, 31, 203, 3639, 2254, 5034, 16730, 22, 273, 5700, 8541, 38, 60, 10525, 300, 5700, 8541, 2501, 10525, 31, 203, 203, 3639, 2583, 12, 24492, 8541, 2501, 10525, 405, 374, 1769, 203, 203, 3639, 327, 203, 5411, 3643, 1211, 203, 7734, 692, 27476, 10477, 18, 2892, 11066, 310, 1211, 12, 203, 10792, 11692, 10477, 18, 16411, 7244, 11066, 310, 1211, 12, 2107, 7385, 21, 16, 16730, 22, 16, 5700, 8541, 38, 60, 10525, 3631, 203, 10792, 5700, 8541, 2501, 10525, 203, 7734, 262, 203, 7734, 294, 11692, 10477, 18, 16411, 7244, 12, 2107, 7385, 21, 16, 16730, 22, 16, 5700, 8541, 38, 60, 10525, 13, 342, 5700, 8541, 2501, 10525, 31, 2 ]
./full_match/4/0xB4b58210DC03c1A29021B296D80E17aD46427393/sources/contracts/NounsToken.sol
* @notice Set the token minter. @dev Only callable by the owner when not locked./
function setMinter(address _minter) external override onlyOwner whenMinterNotLocked { minter = _minter; emit MinterUpdated(_minter); }
769,816
[ 1, 694, 326, 1147, 1131, 387, 18, 225, 5098, 4140, 635, 326, 3410, 1347, 486, 8586, 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, 15430, 2761, 12, 2867, 389, 1154, 387, 13, 3903, 3849, 1338, 5541, 1347, 49, 2761, 1248, 8966, 288, 203, 3639, 1131, 387, 273, 389, 1154, 387, 31, 203, 203, 3639, 3626, 490, 2761, 7381, 24899, 1154, 387, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "../client/node_modules/@openzeppelin/contracts/access/Ownable.sol"; /// @title Systeme de Vote /// @author jw418 /// @notice You can use this contract for only the most basic simulation /// @dev seul le owner peut ajouter des addresses a la WL ou changer le workflow status. /// @custom:experimental This is an experimental contract.(Formation Digitt) contract Voting is Ownable { struct Voter { bool isRegistered; // if true, that person already on the whitelist bool hasVoted; // if true, that person already voted uint256 votedProposalId; // index of the voted proposal } struct Proposal { string description; // descripton de la proposition uint256 voteCount; // number of accumulated votes } /// @dev le workflow status ne va que dans un seul sens (pas de boucle possible) enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } /// @dev on met le workflow statut sur l etape 1 WorkflowStatus public currentStatus = WorkflowStatus.RegisteringVoters; mapping(address => Voter) public voters; mapping(address=> bool) public _whitelist; address[] public addresses; Proposal[] public proposals; uint256 public numberOfProposals; uint256 public winnerId; // les event pour transmettre au front event VoterRegistered(address voterAddress); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); event ProposalRegistered(uint256 proposalId); event Voted(address voter, uint256 proposalId); /// @notice pour ajouter des addresses a la WL /// @param _address address a ajouté a la WL function isWhitelisted(address _address) external onlyOwner { require(currentStatus == WorkflowStatus.RegisteringVoters,"the registration period for the whitelist is over"); require(!voters[_address].isRegistered,"This voters is already registered"); voters[_address].isRegistered = true; addresses.push(_address); emit VoterRegistered(_address); } /// @notice obtenir la liste des adresses sur la WL function getAddresses() public view returns(address[] memory){ return addresses; } /// @notice pour demarrer l'enregistrement des propositions /// @dev une fois la fonction appelée le statut change, on ne peut donc plus ajouter d addreses a la WL!! function startProposalRegistration() external onlyOwner { require(currentStatus == WorkflowStatus.RegisteringVoters,"the current workflow status does not allow you to start registering proposals"); currentStatus = WorkflowStatus.ProposalsRegistrationStarted; emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted); } /// @notice pour déposer des propositions /// @param _proposal string qui contient la description de la proposition function depositProposal(string calldata _proposal) external { require(voters[msg.sender].isRegistered == true, "this address is not whitelisted"); require(currentStatus == WorkflowStatus.ProposalsRegistrationStarted, "registration of proposals is not already open or already close"); proposals.push(Proposal({description: _proposal, voteCount: 0})); emit ProposalRegistered(numberOfProposals); numberOfProposals += 1; } /// @notice pour obtenir la liste des propositions et l'id associé /// @return arrayOfProposals tableau avec les propositions et leur id associés function getArrayOfProposals() external view returns (Proposal[] memory) { Proposal[] memory arrayOfProposals = new Proposal[](proposals.length); for (uint256 i = 0; i < proposals.length; i++) { arrayOfProposals[i] = proposals[i]; } return arrayOfProposals; } /// @notice pour stoper l'enregistrement des propositions function endProposalRegistration() external onlyOwner { require(currentStatus == WorkflowStatus.ProposalsRegistrationStarted, "the current workflow status does not allow you to stop registering proposals" ); currentStatus = WorkflowStatus.ProposalsRegistrationEnded; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded); } /// @notice pour demarrer la session de vote function startVotingSession() external onlyOwner { require(currentStatus == WorkflowStatus.ProposalsRegistrationEnded, "the current workflow status does not allow you to start voting session"); currentStatus = WorkflowStatus.VotingSessionStarted; emit WorkflowStatusChange( WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted ); } /// @notice pour voter /// @param _proposalId uint pour laquelle le votant vote function voteFor(uint256 _proposalId) external { require(voters[msg.sender].isRegistered == true, "this address is not whitelisted"); require(currentStatus == WorkflowStatus.VotingSessionStarted, "the current workflow status does not allow you to vote"); require(!voters[msg.sender].hasVoted, "this address has already voted"); require(_proposalId <= numberOfProposals, "this proposal does not exsit"); proposals[_proposalId].voteCount += 1; voters[msg.sender].hasVoted = true; voters[msg.sender].votedProposalId = _proposalId; emit Voted(msg.sender, _proposalId); } /// @notice met fin a la session de vote function endVotingSession() external onlyOwner { require(currentStatus == WorkflowStatus.VotingSessionStarted, "the current workflow status does not allow you to stop voting session"); currentStatus = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange( WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded ); } /// @notice lance le comptage du vote function countedVotes() external onlyOwner { require(currentStatus == WorkflowStatus.VotingSessionEnded, "the current workflow status does not allow you to counted the votes"); uint256 voteMax; for (uint256 i = 0; i < proposals.length; i++) { // simplification, ne prends pas en compte la possibilité d'une égalié if (proposals[i].voteCount > voteMax) { voteMax = proposals[i].voteCount; winnerId = i; } } currentStatus = WorkflowStatus.VotesTallied; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied); } /// @notice pour obtenir la proposition gagnante /// @return winnerIdAndDescription function getWinner() external view returns (uint256) { require(currentStatus == WorkflowStatus.VotesTallied,"the current workflow status does not allow you to get the winner"); return winnerId; } }
@title Systeme de Vote @author jw418 @notice You can use this contract for only the most basic simulation @dev seul le owner peut ajouter des addresses a la WL ou changer le workflow status. @custom:experimental This is an experimental contract.(Formation Digitt)
contract Voting is Ownable { struct Voter { } struct Proposal { } enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } mapping(address => Voter) public voters; mapping(address=> bool) public _whitelist; address[] public addresses; Proposal[] public proposals; uint256 public numberOfProposals; uint256 public winnerId; event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); event ProposalRegistered(uint256 proposalId); event Voted(address voter, uint256 proposalId); WorkflowStatus public currentStatus = WorkflowStatus.RegisteringVoters; event VoterRegistered(address voterAddress); function isWhitelisted(address _address) external onlyOwner { require(currentStatus == WorkflowStatus.RegisteringVoters,"the registration period for the whitelist is over"); require(!voters[_address].isRegistered,"This voters is already registered"); voters[_address].isRegistered = true; addresses.push(_address); emit VoterRegistered(_address); } function getAddresses() public view returns(address[] memory){ return addresses; } function startProposalRegistration() external onlyOwner { require(currentStatus == WorkflowStatus.RegisteringVoters,"the current workflow status does not allow you to start registering proposals"); currentStatus = WorkflowStatus.ProposalsRegistrationStarted; emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted); } function depositProposal(string calldata _proposal) external { require(voters[msg.sender].isRegistered == true, "this address is not whitelisted"); require(currentStatus == WorkflowStatus.ProposalsRegistrationStarted, "registration of proposals is not already open or already close"); emit ProposalRegistered(numberOfProposals); numberOfProposals += 1; } proposals.push(Proposal({description: _proposal, voteCount: 0})); function getArrayOfProposals() external view returns (Proposal[] memory) { Proposal[] memory arrayOfProposals = new Proposal[](proposals.length); for (uint256 i = 0; i < proposals.length; i++) { arrayOfProposals[i] = proposals[i]; } return arrayOfProposals; } function getArrayOfProposals() external view returns (Proposal[] memory) { Proposal[] memory arrayOfProposals = new Proposal[](proposals.length); for (uint256 i = 0; i < proposals.length; i++) { arrayOfProposals[i] = proposals[i]; } return arrayOfProposals; } function endProposalRegistration() external onlyOwner { require(currentStatus == WorkflowStatus.ProposalsRegistrationStarted, "the current workflow status does not allow you to stop registering proposals" ); currentStatus = WorkflowStatus.ProposalsRegistrationEnded; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded); } function startVotingSession() external onlyOwner { require(currentStatus == WorkflowStatus.ProposalsRegistrationEnded, "the current workflow status does not allow you to start voting session"); currentStatus = WorkflowStatus.VotingSessionStarted; emit WorkflowStatusChange( WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted ); } function voteFor(uint256 _proposalId) external { require(voters[msg.sender].isRegistered == true, "this address is not whitelisted"); require(currentStatus == WorkflowStatus.VotingSessionStarted, "the current workflow status does not allow you to vote"); require(!voters[msg.sender].hasVoted, "this address has already voted"); require(_proposalId <= numberOfProposals, "this proposal does not exsit"); proposals[_proposalId].voteCount += 1; voters[msg.sender].hasVoted = true; voters[msg.sender].votedProposalId = _proposalId; emit Voted(msg.sender, _proposalId); } function endVotingSession() external onlyOwner { require(currentStatus == WorkflowStatus.VotingSessionStarted, "the current workflow status does not allow you to stop voting session"); currentStatus = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange( WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded ); } function countedVotes() external onlyOwner { require(currentStatus == WorkflowStatus.VotingSessionEnded, "the current workflow status does not allow you to counted the votes"); uint256 voteMax; for (uint256 i = 0; i < proposals.length; i++) { if (proposals[i].voteCount > voteMax) { voteMax = proposals[i].voteCount; winnerId = i; } } currentStatus = WorkflowStatus.VotesTallied; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied); } function countedVotes() external onlyOwner { require(currentStatus == WorkflowStatus.VotingSessionEnded, "the current workflow status does not allow you to counted the votes"); uint256 voteMax; for (uint256 i = 0; i < proposals.length; i++) { if (proposals[i].voteCount > voteMax) { voteMax = proposals[i].voteCount; winnerId = i; } } currentStatus = WorkflowStatus.VotesTallied; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied); } function countedVotes() external onlyOwner { require(currentStatus == WorkflowStatus.VotingSessionEnded, "the current workflow status does not allow you to counted the votes"); uint256 voteMax; for (uint256 i = 0; i < proposals.length; i++) { if (proposals[i].voteCount > voteMax) { voteMax = proposals[i].voteCount; winnerId = i; } } currentStatus = WorkflowStatus.VotesTallied; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied); } function getWinner() external view returns (uint256) { require(currentStatus == WorkflowStatus.VotesTallied,"the current workflow status does not allow you to get the winner"); return winnerId; } }
984,871
[ 1, 3163, 73, 443, 27540, 225, 26203, 24, 2643, 225, 4554, 848, 999, 333, 6835, 364, 1338, 326, 4486, 5337, 14754, 225, 695, 332, 884, 3410, 2804, 322, 24787, 14068, 2832, 6138, 279, 7125, 678, 48, 16694, 9435, 264, 884, 6095, 1267, 18, 632, 3662, 30, 18142, 287, 1220, 353, 392, 23070, 6835, 18, 12, 12624, 11678, 305, 88, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 776, 17128, 353, 14223, 6914, 288, 203, 203, 203, 565, 1958, 776, 20005, 288, 203, 565, 289, 203, 203, 565, 1958, 19945, 288, 203, 565, 289, 203, 203, 565, 2792, 11363, 1482, 288, 203, 3639, 5433, 310, 58, 352, 414, 16, 203, 3639, 1186, 22536, 7843, 9217, 16, 203, 3639, 1186, 22536, 7843, 28362, 16, 203, 3639, 776, 17128, 2157, 9217, 16, 203, 3639, 776, 17128, 2157, 28362, 16, 203, 3639, 776, 6366, 56, 454, 2092, 203, 565, 289, 203, 203, 203, 565, 2874, 12, 2867, 516, 776, 20005, 13, 1071, 331, 352, 414, 31, 203, 565, 2874, 12, 2867, 9207, 1426, 13, 1071, 389, 20409, 31, 203, 565, 1758, 8526, 1071, 6138, 31, 203, 565, 19945, 8526, 1071, 450, 22536, 31, 203, 565, 2254, 5034, 1071, 7922, 626, 22536, 31, 203, 565, 2254, 5034, 1071, 5657, 1224, 548, 31, 203, 203, 565, 871, 11363, 1482, 3043, 12, 8484, 1482, 2416, 1482, 16, 203, 565, 11363, 1482, 394, 1482, 1769, 203, 565, 871, 19945, 10868, 12, 11890, 5034, 14708, 548, 1769, 377, 203, 565, 871, 776, 16474, 12, 2867, 331, 20005, 16, 2254, 5034, 14708, 548, 1769, 203, 203, 377, 203, 565, 11363, 1482, 1071, 783, 1482, 273, 11363, 1482, 18, 3996, 310, 58, 352, 414, 31, 203, 565, 871, 776, 20005, 10868, 12, 2867, 331, 20005, 1887, 1769, 377, 203, 565, 445, 353, 18927, 329, 12, 2867, 389, 2867, 13, 3903, 1338, 5541, 288, 1171, 203, 3639, 2583, 12, 2972, 1482, 422, 11363, 1482, 18, 3996, 310, 58, 352, 414, 10837, 5787, 2 ]
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY886() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF698(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER57(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE343(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE196(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM951(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER641(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL12(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER192() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function TOTALSUPPLY886() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF698(address account) public view returns (uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER57(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER194(_MSGSENDER192(), recipient, amount); return true; } function ALLOWANCE343(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE196(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, amount); return true; } function TRANSFERFROM951(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER194(sender, recipient, amount); _APPROVE501(sender, _MSGSENDER192(), _allowances[sender][_MSGSENDER192()].SUB39(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE73(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].ADD377(addedValue)); return true; } function DECREASEALLOWANCE445(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].SUB39(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER194(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB39(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD377(amount); emit TRANSFER641(sender, recipient, amount); } function _MINT845(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD377(amount); _balances[account] = _balances[account].ADD377(amount); emit TRANSFER641(address(0), account, amount); } function _BURN745(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB39(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB39(amount); emit TRANSFER641(account, address(0), amount); } function _APPROVE501(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING 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 APPROVAL12(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; uint256 private TokenmaxSupply = 2500*10**18; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME395() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS28() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function MAXSUPPLY198() public view returns (uint256) { //inject NONSTANDARD NAMING return TokenmaxSupply; } } library SafeMath { function ADD377(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB39(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB39(a, b, "SafeMath: subtraction overflow"); } function SUB39(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL593(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV750(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV750(a, b, "SafeMath: division by zero"); } function DIV750(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function ISCONTRACT755(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function SAFETRANSFER74(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFER57.selector, to, value)); } function SAFETRANSFERFROM551(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFERFROM951.selector, from, to, value)); } function SAFEAPPROVE429(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE343(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.APPROVE196.selector, spender, value)); } function CALLOPTIONALRETURN536(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT755(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract YFIG is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("yfipaprika.finance", "YFIG", 18) { governance = tx.origin; } function MINT662(address account, uint256 amount) public { //inject NONSTANDARD NAMING require(TOTALSUPPLY886() + amount <= MAXSUPPLY198(), "Supply Max Reached"); require(minters[msg.sender], "!minter"); _MINT845(account, amount); } function BURN585(uint256 amount) external { //inject NONSTANDARD NAMING require(amount != 0, "you cannot burn zero amount"); _BURN745(msg.sender, amount); } function SETGOVERNANCE8(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function ADDMINTER497(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = true; } function REMOVEMINTER463(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
inject NONSTANDARD NAMING
function SUB39(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
7,321,039
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10025, 5520, 12, 11890, 279, 16, 2254, 324, 16, 533, 3778, 9324, 13, 2713, 16618, 1135, 261, 11890, 13, 288, 202, 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 ]
/* Copyright 2017-2018 RigoBlock, Rigo Investment Sagl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.0; import { AuthorityFace as Authority } from "../authorities/Authority/AuthorityFace.sol"; import { ExchangesAuthorityFace as DexAuth } from "../authorities/ExchangesAuthority/ExchangesAuthorityFace.sol"; import { DragoEventfulFace } from "./DragoEventfulFace.sol"; /// @title Drago Eventful contract. /// @author Gabriele Rigo - <[email protected]> // solhint-disable-next-line contract DragoEventful is DragoEventfulFace { string public constant VERSION = 'DH0.4.2'; address public AUTHORITY; event BuyDrago( address indexed drago, address indexed from, address indexed to, uint256 amount, uint256 revenue, bytes name, bytes symbol ); event SellDrago( address indexed drago, address indexed from, address indexed to, uint256 amount, uint256 revenue, bytes name, bytes symbol ); event NewRatio( address indexed drago, address indexed from, uint256 newRatio ); event NewNAV( address indexed drago, address indexed from, address indexed to, uint256 sellPrice, uint256 buyPrice ); event NewFee( address indexed drago, address indexed group, address indexed who, uint256 transactionFee ); event NewCollector( address indexed drago, address indexed group, address indexed who, address feeCollector ); event DragoDao( address indexed drago, address indexed from, address indexed to, address dragoDao ); event DepositExchange( address indexed drago, address indexed exchange, address indexed token, uint256 value, uint256 amount ); event WithdrawExchange( address indexed drago, address indexed exchange, address indexed token, uint256 value, uint256 amount ); event OrderExchange( address indexed drago, address indexed exchange, address indexed cfd, uint256 value, uint256 revenue ); event TradeExchange( address indexed drago, address indexed exchange, address tokenGet, address tokenGive, uint256 amountGet, uint256 amountGive, address get ); event CancelOrder( address indexed drago, address indexed exchange, address indexed cfd, uint256 value, uint256 id ); event DealFinalized( address indexed drago, address indexed exchange, address indexed cfd, uint256 value, uint256 id ); event CustomDragoLog( bytes4 indexed method, bytes encodedParams ); event CustomDragoLog2( bytes4 indexed methodHash, bytes32 indexed topic2, bytes32 indexed topic3, bytes encodedParams ); event DragoCreated( address indexed drago, address indexed group, address indexed owner, uint256 dragoId, string name, string symbol ); modifier approvedFactoryOnly(address _factory) { Authority auth = Authority(AUTHORITY); require(auth.isWhitelistedFactory(_factory)); _; } modifier approvedDragoOnly(address _drago) { Authority auth = Authority(AUTHORITY); require(auth.isWhitelistedDrago(_drago)); _; } modifier approvedExchangeOnly(address _exchange) { Authority auth = Authority(AUTHORITY); require( DexAuth(auth.getExchangesAuthority()) .isWhitelistedExchange(_exchange)); _; } modifier approvedUserOnly(address _user) { Authority auth = Authority(AUTHORITY); require(auth.isWhitelistedUser(_user)); _; } modifier approvedAsset(address _asset) { Authority auth = Authority(AUTHORITY); require( DexAuth(auth.getExchangesAuthority()) .isWhitelistedAsset(_asset)); _; } constructor(address _authority) public { AUTHORITY = _authority; } /* * CORE FUNCTIONS */ /// @dev Logs a Buy Drago event. /// @param _who Address of who is buying /// @param _targetDrago Address of the target drago /// @param _value Value of the transaction in Ether /// @param _amount Number of shares purchased /// @return Bool the transaction executed successfully function buyDrago( address _who, address _targetDrago, uint256 _value, uint256 _amount, bytes calldata _name, bytes calldata _symbol) external approvedDragoOnly(msg.sender) returns (bool success) { buyDragoInternal(_targetDrago, _who, msg.sender, _value, _amount, _name, _symbol); return true; } /// @dev Logs a Sell Drago event. /// @param _who Address of who is selling /// @param _targetDrago Address of the target drago /// @param _amount Number of shares purchased /// @param _revenue Value of the transaction in Ether /// @return Bool the transaction executed successfully function sellDrago( address _who, address _targetDrago, uint256 _amount, uint256 _revenue, bytes calldata _name, bytes calldata _symbol) external approvedDragoOnly(msg.sender) returns(bool success) { require(_amount > 0); sellDragoInternal(_targetDrago, _who, msg.sender, _amount, _revenue, _name, _symbol); return true; } /// @dev Logswhen rigoblock dao changes fee split. /// @param _who Address of the caller /// @param _targetDrago Address of the target drago /// @param _ratio Ratio number from 0 to 100 /// @return Bool the transaction executed successfully function changeRatio( address _who, address _targetDrago, uint256 _ratio) external approvedDragoOnly(msg.sender) returns(bool success) { require(_ratio > 0); emit NewRatio(_targetDrago, _who, _ratio); return true; } /// @dev Logs when wizard changes fee collector address /// @param _who Address of the caller /// @param _targetDrago Address of the target Drago /// @param _feeCollector Address of the new fee collector /// @return Bool the transaction executed successfully function changeFeeCollector( address _who, address _targetDrago, address _feeCollector) external approvedDragoOnly(msg.sender) approvedUserOnly(_who) returns(bool success) { emit NewCollector(_targetDrago, msg.sender, _who, _feeCollector); return true; } /// @dev Logs a change in the drago dao of an approved vault /// @param _who Address of the caller /// @param _targetDrago Address of the drago /// @param _dragoDao Address of the new drago dao /// @return Bool the transaction executed successfully function changeDragoDao( address _who, address _targetDrago, address _dragoDao) external approvedDragoOnly(msg.sender) approvedUserOnly(_who) returns(bool success) { emit DragoDao(_targetDrago, msg.sender, _who, _dragoDao); return true; } /// @dev Logs a Set Drago Price event /// @param _who Address of the caller /// @param _targetDrago Address of the target Drago /// @param _sellPrice Value of the price of one share in wei /// @param _buyPrice Value of the price of one share in wei /// @return Bool the transaction executed successfully function setDragoPrice( address _who, address _targetDrago, uint256 _sellPrice, uint256 _buyPrice) external approvedDragoOnly(msg.sender) returns(bool success) { require(_sellPrice > 10 finney && _buyPrice > 10 finney); emit NewNAV(_targetDrago, msg.sender, _who, _sellPrice, _buyPrice); return true; } /// @dev Logs a modification of the transaction fee event /// @param _who Address of the caller /// @param _targetDrago Address of the target Drago /// @param _transactionFee Value of the transaction fee in basis points /// @return Bool the transaction executed successfully function setTransactionFee( address _who, address _targetDrago, uint256 _transactionFee) external approvedDragoOnly(msg.sender) approvedUserOnly(_who) returns(bool success) { emit NewFee(_targetDrago, msg.sender, _who, _transactionFee); return true; } /// @dev Logs a Drago Deposit To Exchange event /// @param _who Address of the caller /// @param _targetDrago Address of the target Drago /// @param _exchange Address of the exchange /// @param _token Address of the deposited token /// @param _value Number of deposited tokens /// @return Bool the transaction executed successfully function depositToExchange( address _who, address _targetDrago, address _exchange, address _token, uint256 _value) external approvedUserOnly(_who) approvedDragoOnly(msg.sender) approvedExchangeOnly(_exchange) returns(bool success) { emit DepositExchange(_targetDrago, _exchange, _token, _value, 0); return true; } /// @dev Logs a Drago Withdraw From Exchange event /// @param _who Address of the caller /// @param _targetDrago Address of the target Drago /// @param _exchange Address of the exchange /// @param _token Address of the withdrawn token /// @param _value Number of withdrawn tokens /// @return Bool the transaction executed successfully function withdrawFromExchange( address _who, address _targetDrago, address _exchange, address _token, uint256 _value) external approvedUserOnly(_who) approvedDragoOnly(msg.sender) approvedExchangeOnly(_exchange) returns(bool success) { emit WithdrawExchange(_targetDrago, _exchange, _token, _value, 0); return true; } /// @dev Logs an event sent from a drago /// @param _methodHash the method of the call /// @param _encodedParams the arbitrary data array /// @return Bool the transaction executed successfully function customDragoLog( bytes4 _methodHash, bytes calldata _encodedParams) external approvedDragoOnly(msg.sender) returns (bool success) { emit CustomDragoLog(_methodHash, _encodedParams); return true; } /// @dev Logs an event sent from a drago /// @param _methodHash the method of the call /// @param _encodedParams the arbitrary data array /// @return Bool the transaction executed successfully function customDragoLog2( bytes4 _methodHash, bytes32 topic2, bytes32 topic3, bytes calldata _encodedParams) external approvedDragoOnly(msg.sender) returns (bool success) { emit CustomDragoLog2(_methodHash, topic2, topic3, _encodedParams); return true; } /// @dev Logs an event sent from an approved exchange /// @param _methodHash the method of the call /// @param _encodedParams the arbitrary data array /// @return Bool the transaction executed successfully function customExchangeLog( bytes4 _methodHash, bytes calldata _encodedParams) external approvedExchangeOnly(msg.sender) returns (bool success) { emit CustomDragoLog(_methodHash, _encodedParams); return true; } /// @dev Logs an event sent from an approved exchange /// @param _methodHash the method of the call /// @param _encodedParams the arbitrary data array /// @return Bool the transaction executed successfully function customExchangeLog2( bytes4 _methodHash, bytes32 topic2, bytes32 topic3, bytes calldata _encodedParams) external approvedExchangeOnly(msg.sender) returns (bool success) { emit CustomDragoLog2(_methodHash, topic2, topic3, _encodedParams); return true; } /// @dev Logs a new Drago creation by factory /// @param _who Address of the caller /// @param _newDrago Address of the new Drago /// @param _name String of the name of the new drago /// @param _symbol String of the symbol of the new drago /// @param _dragoId Number of the new drago Id /// @return Bool the transaction executed successfully function createDrago( address _who, address _newDrago, string calldata _name, string calldata _symbol, uint256 _dragoId) external approvedFactoryOnly(msg.sender) returns(bool success) { createDragoInternal(_newDrago, msg.sender, _who, _dragoId, _name, _symbol); return true; } /* * INTERNAL FUNCTIONS */ /// @dev Logs a purchase event /// @param _who Address of the caller /// @param _targetDrago Address of the drago /// @param _factory Address of the factory /// @param _value Value of transaction in wei /// @param _amount Number of new tokens /// @param _name Hex encoded bytes of the name /// @param _symbol Hex encoded bytes of the symbol function buyDragoInternal( address _targetDrago, address _who, address _factory, uint256 _value, uint256 _amount, bytes memory _name, bytes memory _symbol) internal { emit BuyDrago(_targetDrago, _who, _factory, _value, _amount, _name, _symbol); } /// @dev Logs a sale event /// @param _who Address of the caller /// @param _targetDrago Address of the drago /// @param _factory Address of the factory /// @param _amount Number of burnt tokens /// @param _revenue Value of transaction in wei /// @param _name Hex encoded bytes of the name /// @param _symbol Hex encoded bytes of the symbol function sellDragoInternal( address _targetDrago, address _who, address _factory, uint256 _amount, uint256 _revenue, bytes memory _name, bytes memory _symbol) internal { emit SellDrago(_targetDrago, _who, _factory, _amount, _revenue, _name, _symbol); } /// @dev Logs a new drago creation by factory /// @param _who Address of the caller /// @param _newDrago Address of the new drago /// @param _factory Address of the factory /// @param _name Bytes array of the name /// @param _symbol Bytes array of the symbol /// @param _dragoId Number of the pool in registry function createDragoInternal( address _newDrago, address _factory, address _who, uint256 _dragoId, string memory _name, string memory _symbol) internal { emit DragoCreated(_newDrago, _factory, _who, _dragoId, _name, _symbol); } }
@title Drago Eventful contract. @author Gabriele Rigo - <[email protected]> solhint-disable-next-line
contract DragoEventful is DragoEventfulFace { string public constant VERSION = 'DH0.4.2'; address public AUTHORITY; event BuyDrago( address indexed drago, address indexed from, address indexed to, uint256 amount, uint256 revenue, bytes name, bytes symbol ); event SellDrago( address indexed drago, address indexed from, address indexed to, uint256 amount, uint256 revenue, bytes name, bytes symbol ); event NewRatio( address indexed drago, address indexed from, uint256 newRatio ); event NewNAV( address indexed drago, address indexed from, address indexed to, uint256 sellPrice, uint256 buyPrice ); event NewFee( address indexed drago, address indexed group, address indexed who, uint256 transactionFee ); event NewCollector( address indexed drago, address indexed group, address indexed who, address feeCollector ); event DragoDao( address indexed drago, address indexed from, address indexed to, address dragoDao ); event DepositExchange( address indexed drago, address indexed exchange, address indexed token, uint256 value, uint256 amount ); event WithdrawExchange( address indexed drago, address indexed exchange, address indexed token, uint256 value, uint256 amount ); event OrderExchange( address indexed drago, address indexed exchange, address indexed cfd, uint256 value, uint256 revenue ); event TradeExchange( address indexed drago, address indexed exchange, address tokenGet, address tokenGive, uint256 amountGet, uint256 amountGive, address get ); event CancelOrder( address indexed drago, address indexed exchange, address indexed cfd, uint256 value, uint256 id ); event DealFinalized( address indexed drago, address indexed exchange, address indexed cfd, uint256 value, uint256 id ); event CustomDragoLog( bytes4 indexed method, bytes encodedParams ); event CustomDragoLog2( bytes4 indexed methodHash, bytes32 indexed topic2, bytes32 indexed topic3, bytes encodedParams ); event DragoCreated( address indexed drago, address indexed group, address indexed owner, uint256 dragoId, string name, string symbol ); import { AuthorityFace as Authority } from "../authorities/Authority/AuthorityFace.sol"; import { ExchangesAuthorityFace as DexAuth } from "../authorities/ExchangesAuthority/ExchangesAuthorityFace.sol"; import { DragoEventfulFace } from "./DragoEventfulFace.sol"; modifier approvedFactoryOnly(address _factory) { Authority auth = Authority(AUTHORITY); require(auth.isWhitelistedFactory(_factory)); _; } modifier approvedDragoOnly(address _drago) { Authority auth = Authority(AUTHORITY); require(auth.isWhitelistedDrago(_drago)); _; } modifier approvedExchangeOnly(address _exchange) { Authority auth = Authority(AUTHORITY); require( DexAuth(auth.getExchangesAuthority()) .isWhitelistedExchange(_exchange)); _; } modifier approvedUserOnly(address _user) { Authority auth = Authority(AUTHORITY); require(auth.isWhitelistedUser(_user)); _; } modifier approvedAsset(address _asset) { Authority auth = Authority(AUTHORITY); require( DexAuth(auth.getExchangesAuthority()) .isWhitelistedAsset(_asset)); _; } constructor(address _authority) public { AUTHORITY = _authority; } function buyDrago( address _who, address _targetDrago, uint256 _value, uint256 _amount, bytes calldata _name, bytes calldata _symbol) external approvedDragoOnly(msg.sender) returns (bool success) { buyDragoInternal(_targetDrago, _who, msg.sender, _value, _amount, _name, _symbol); return true; } function sellDrago( address _who, address _targetDrago, uint256 _amount, uint256 _revenue, bytes calldata _name, bytes calldata _symbol) external approvedDragoOnly(msg.sender) returns(bool success) { require(_amount > 0); sellDragoInternal(_targetDrago, _who, msg.sender, _amount, _revenue, _name, _symbol); return true; } function changeRatio( address _who, address _targetDrago, uint256 _ratio) external approvedDragoOnly(msg.sender) returns(bool success) { require(_ratio > 0); emit NewRatio(_targetDrago, _who, _ratio); return true; } function changeFeeCollector( address _who, address _targetDrago, address _feeCollector) external approvedDragoOnly(msg.sender) approvedUserOnly(_who) returns(bool success) { emit NewCollector(_targetDrago, msg.sender, _who, _feeCollector); return true; } function changeDragoDao( address _who, address _targetDrago, address _dragoDao) external approvedDragoOnly(msg.sender) approvedUserOnly(_who) returns(bool success) { emit DragoDao(_targetDrago, msg.sender, _who, _dragoDao); return true; } function setDragoPrice( address _who, address _targetDrago, uint256 _sellPrice, uint256 _buyPrice) external approvedDragoOnly(msg.sender) returns(bool success) { require(_sellPrice > 10 finney && _buyPrice > 10 finney); emit NewNAV(_targetDrago, msg.sender, _who, _sellPrice, _buyPrice); return true; } function setTransactionFee( address _who, address _targetDrago, uint256 _transactionFee) external approvedDragoOnly(msg.sender) approvedUserOnly(_who) returns(bool success) { emit NewFee(_targetDrago, msg.sender, _who, _transactionFee); return true; } function depositToExchange( address _who, address _targetDrago, address _exchange, address _token, uint256 _value) external approvedUserOnly(_who) approvedDragoOnly(msg.sender) approvedExchangeOnly(_exchange) returns(bool success) { emit DepositExchange(_targetDrago, _exchange, _token, _value, 0); return true; } function withdrawFromExchange( address _who, address _targetDrago, address _exchange, address _token, uint256 _value) external approvedUserOnly(_who) approvedDragoOnly(msg.sender) approvedExchangeOnly(_exchange) returns(bool success) { emit WithdrawExchange(_targetDrago, _exchange, _token, _value, 0); return true; } function customDragoLog( bytes4 _methodHash, bytes calldata _encodedParams) external approvedDragoOnly(msg.sender) returns (bool success) { emit CustomDragoLog(_methodHash, _encodedParams); return true; } function customDragoLog2( bytes4 _methodHash, bytes32 topic2, bytes32 topic3, bytes calldata _encodedParams) external approvedDragoOnly(msg.sender) returns (bool success) { emit CustomDragoLog2(_methodHash, topic2, topic3, _encodedParams); return true; } function customExchangeLog( bytes4 _methodHash, bytes calldata _encodedParams) external approvedExchangeOnly(msg.sender) returns (bool success) { emit CustomDragoLog(_methodHash, _encodedParams); return true; } function customExchangeLog2( bytes4 _methodHash, bytes32 topic2, bytes32 topic3, bytes calldata _encodedParams) external approvedExchangeOnly(msg.sender) returns (bool success) { emit CustomDragoLog2(_methodHash, topic2, topic3, _encodedParams); return true; } function createDrago( address _who, address _newDrago, string calldata _name, string calldata _symbol, uint256 _dragoId) external approvedFactoryOnly(msg.sender) returns(bool success) { createDragoInternal(_newDrago, msg.sender, _who, _dragoId, _name, _symbol); return true; } function buyDragoInternal( address _targetDrago, address _who, address _factory, uint256 _value, uint256 _amount, bytes memory _name, bytes memory _symbol) internal { emit BuyDrago(_targetDrago, _who, _factory, _value, _amount, _name, _symbol); } function sellDragoInternal( address _targetDrago, address _who, address _factory, uint256 _amount, uint256 _revenue, bytes memory _name, bytes memory _symbol) internal { emit SellDrago(_targetDrago, _who, _factory, _amount, _revenue, _name, _symbol); } function createDragoInternal( address _newDrago, address _factory, address _who, uint256 _dragoId, string memory _name, string memory _symbol) internal { emit DragoCreated(_newDrago, _factory, _who, _dragoId, _name, _symbol); } }
1,085,090
[ 1, 11728, 83, 2587, 2706, 6835, 18, 225, 611, 378, 566, 6516, 534, 17626, 300, 411, 75, 378, 36, 86, 360, 947, 739, 18, 832, 34, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 28425, 83, 1133, 2706, 353, 28425, 83, 1133, 2706, 11824, 288, 203, 203, 565, 533, 1071, 5381, 8456, 273, 296, 16501, 20, 18, 24, 18, 22, 13506, 203, 203, 565, 1758, 1071, 12790, 14751, 31, 203, 203, 565, 871, 605, 9835, 11728, 83, 12, 203, 3639, 1758, 8808, 8823, 83, 16, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 1758, 8808, 358, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 283, 24612, 16, 203, 3639, 1731, 508, 16, 203, 3639, 1731, 3273, 203, 565, 11272, 203, 203, 565, 871, 348, 1165, 11728, 83, 12, 203, 3639, 1758, 8808, 8823, 83, 16, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 1758, 8808, 358, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 283, 24612, 16, 203, 3639, 1731, 508, 16, 203, 3639, 1731, 3273, 203, 565, 11272, 203, 203, 565, 871, 1166, 8541, 12, 203, 3639, 1758, 8808, 8823, 83, 16, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 2254, 5034, 394, 8541, 203, 565, 11272, 203, 203, 565, 871, 1166, 50, 5856, 12, 203, 3639, 1758, 8808, 8823, 83, 16, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 1758, 8808, 358, 16, 203, 3639, 2254, 5034, 357, 80, 5147, 16, 203, 3639, 2254, 5034, 30143, 5147, 203, 565, 11272, 203, 203, 565, 871, 1166, 14667, 12, 203, 3639, 1758, 8808, 8823, 83, 16, 203, 3639, 1758, 8808, 1041, 16, 203, 3639, 1758, 8808, 10354, 16, 203, 3639, 2254, 5034, 2492, 14667, 203, 565, 11272, 203, 203, 565, 871, 2 ]
pragma solidity ^0.4.15; // File: contracts/Managed.sol /* Provides support and utilities for contract management */ contract Managed { address public manager; address public newManager; event ManagerUpdate(address _prevManager, address _newManager); /** @dev constructor */ function Managed() { manager = msg.sender; } // allows execution by the manager only modifier managerOnly { assert(msg.sender == manager); _; } /** @dev allows transferring the contract management the new manager still needs to accept the transfer can only be called by the contract manager @param _newManager new contract manager */ function transferManagement(address _newManager) public managerOnly { require(_newManager != manager); newManager = _newManager; } /** @dev used by a new manager to accept a management transfer */ function acceptManagement() public { require(msg.sender == newManager); ManagerUpdate(manager, newManager); manager = newManager; newManager = 0x0; } } // File: contracts/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Managed { 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 Manager to pause, triggers stopped state */ function pause() managerOnly whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the Manager to unpause, returns to normal state */ function unpause() managerOnly whenPaused returns (bool) { paused = false; Unpause(); return true; } } // File: contracts/Utils.sol /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } // File: contracts/interfaces/IERC20Token.sol /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public constant returns (string name) { name; } function symbol() public constant returns (string symbol) { symbol; } function decimals() public constant returns (uint8 decimals) { decimals; } function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; } function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; } 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); } // File: contracts/ERC20Token.sol /** ERC20 Standard Token implementation */ contract ERC20Token is IERC20Token, Utils { string public standard = 'Token 0.1'; string public name = ''; string public symbol = ''; uint8 public decimals = 0; uint256 public totalSupply = 0; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** @dev constructor @param _name token name @param _symbol token symbol @param _decimals decimal points, for display purposes */ function ERC20Token(string _name, string _symbol, uint8 _decimals) { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input name = _name; symbol = _symbol; decimals = _decimals; } /** @dev send coins throws on any error rather then return a false flag to minimize user errors @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) { balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; } /** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) { allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); return true; } /** @dev allow another account/contract to spend some tokens on your behalf throws on any error rather then return a false flag to minimize user errors also, to minimize the risk of the approve/transferFrom attack vector (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value @param _spender approved address @param _value allowance amount @return true if the approval was successful, false if it wasn't */ function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) { // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal require(_value == 0 || allowance[msg.sender][_spender] == 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } // File: contracts/interfaces/IOwned.sol /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public constant returns (address owner) { owner; } function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/Owned.sol /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address _prevOwner, address _newOwner); /** @dev constructor */ function Owned() { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } } // File: contracts/interfaces/ITokenHolder.sol /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/TokenHolder.sol /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned, Utils { /** @dev constructor */ function TokenHolder() { } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } // File: contracts/interfaces/ISmartToken.sol /* Smart Token interface */ contract ISmartToken is ITokenHolder, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } // File: contracts/SmartToken.sol /* Smart Token v0.3 'Owned' is specified here for readability reasons */ contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder { string public version = '0.3'; bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not // triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory event NewSmartToken(address _token); // triggered when the total supply is increased event Issuance(uint256 _amount); // triggered when the total supply is decreased event Destruction(uint256 _amount); /** @dev constructor @param _name token name @param _symbol token short symbol, minimum 1 character @param _decimals for display purposes only */ function SmartToken(string _name, string _symbol, uint8 _decimals) ERC20Token(_name, _symbol, _decimals) { NewSmartToken(address(this)); } // allows execution only when transfers aren't disabled modifier transfersAllowed { assert(transfersEnabled); _; } /** @dev disables/enables transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTransfers(bool _disable) public ownerOnly { transfersEnabled = !_disable; } /** @dev increases the token supply and sends the new tokens to an account can only be called by the contract owner @param _to account to receive the new amount @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) public ownerOnly validAddress(_to) notThis(_to) { totalSupply = safeAdd(totalSupply, _amount); balanceOf[_to] = safeAdd(balanceOf[_to], _amount); Issuance(_amount); Transfer(this, _to, _amount); } /** @dev removes tokens from an account and decreases the token supply can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account @param _from account to remove the amount from @param _amount amount to decrease the supply by */ function destroy(address _from, uint256 _amount) public { require(msg.sender == _from || msg.sender == owner); // validate input balanceOf[_from] = safeSub(balanceOf[_from], _amount); totalSupply = safeSub(totalSupply, _amount); Transfer(_from, this, _amount); Destruction(_amount); } // ERC20 standard method overrides with some extra functionality /** @dev send coins throws on any error rather then return a false flag to minimize user errors in addition to the standard checks, the function throws if transfers are disabled @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transfer(_to, _value)); return true; } /** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors in addition to the standard checks, the function throws if transfers are disabled @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transferFrom(_from, _to, _value)); return true; } } // File: contracts/SmartTokenController.sol /* The smart token controller is an upgradable part of the smart token that allows more functionality as well as fixes for bugs/exploits. Once it accepts ownership of the token, it becomes the token's sole controller that can execute any of its functions. To upgrade the controller, ownership must be transferred to a new controller, along with any relevant data. The smart token must be set on construction and cannot be changed afterwards. Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access. Note that the controller can transfer token ownership to a new controller that doesn't allow executing any function on the token, for a trustless solution. Doing that will also remove the owner's ability to upgrade the controller. */ contract SmartTokenController is TokenHolder { ISmartToken public token; // smart token /** @dev constructor */ function SmartTokenController(ISmartToken _token) validAddress(_token) { token = _token; } // ensures that the controller is the token's owner modifier active() { assert(token.owner() == address(this)); _; } // ensures that the controller is not the token's owner modifier inactive() { assert(token.owner() != address(this)); _; } /** @dev allows transferring the token ownership the new owner still need to accept the transfer can only be called by the contract owner @param _newOwner new token owner */ function transferTokenOwnership(address _newOwner) public ownerOnly { token.transferOwnership(_newOwner); } /** @dev used by a new owner to accept a token ownership transfer can only be called by the contract owner */ function acceptTokenOwnership() public ownerOnly { token.acceptOwnership(); } /** @dev disables/enables token transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTokenTransfers(bool _disable) public ownerOnly { token.disableTransfers(_disable); } /** @dev withdraws tokens held by the token and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawFromToken(IERC20Token _token, address _to, uint256 _amount) public ownerOnly { token.withdrawTokens(_token, _to, _amount); } } // File: contracts/CrowdsaleController.sol /* The CrowdsaleController allows contributing ether in exchange for Rootcoin tokens The price remains fixed for the entire duration of the crowdsale Presale contributes are allocated (manually) with additional 20% tokens from the beneficiary tokens. Presale contribute mst use pre-verified addresses. (KYC) */ contract CrowdsaleController is SmartTokenController, Managed, Pausable { uint256 public constant DURATION = 14 days; // crowdsale duration uint256 public constant TOKEN_PRICE_N = 1; // initial price in wei (numerator) uint256 public constant TOKEN_PRICE_D = 1000; // initial price in wei (denominator) (1000 wei equals 1 token) uint256 public constant MAX_GAS_PRICE = 50000000000 wei; // maximum gas price for contribution transactions uint256 public constant MAX_CONTRIBUTION = 40 ether; // maximum ether allowed to contribute by an unauthorized single account uint256 public constant SOFTCAP_GRACE_DURATION = 10;//86400; // crowdsale softcap reached grace duration in seconds (24 hours) (use 8 seconds for tests) uint256 public TOTAL_ETHER_CAP = 110000 ether; // overall ether contribution cap. use 1100000 for test uint256 public TOTAL_ETHER_SOFT_CAP = 100000 ether; // overall ether contribution soft cap. use 1000000 for test //Presale constants uint256 public constant PRESALE_DURATION = 14 days; // pressale duration uint256 public constant PRESALE_MIN_CONTRIBUTION = 200 ether; // pressale min contribution //Token constants string public constant TOKEN_NAME = "Rootcoin"; //Token name string public constant TOKEN_SYM = "RCT"; //Token symbol uint8 public constant TOKEN_DEC = 18; //Token decimals //State variables uint256 public startTime = 0; // crowdsale start time (in seconds) uint256 public endTime = 0; // crowdsale end time (in seconds) uint256 public totalEtherContributed = 0; // ether contributed so far address public beneficiary = 0x0; // address to receive all ether contributions mapping(address => bool) public whiteList; //whitelist of accounts that can participate in presale and also contribute more than MAX_CONTRIBUTION uint256 public numOfContributors = 0; // public contributors counter // triggered on each contribution event Contribution(address indexed _contributor, uint256 _amount, uint256 _return); /** @dev constructor @param _startTime crowdsale start time @param _beneficiary address to receive all ether contributions */ function CrowdsaleController(uint256 _startTime, address _beneficiary) SmartTokenController(new SmartToken(TOKEN_NAME, TOKEN_SYM, TOKEN_DEC)) validAddress(_beneficiary) earlierThan(_startTime) { startTime = _startTime; endTime = startTime + DURATION; beneficiary = _beneficiary; token.disableTransfers(true); } // verifies that the gas price is lower than 50 gwei modifier validGasPrice() { assert(tx.gasprice <= MAX_GAS_PRICE); _; } // ensures that it's earlier than the given time modifier earlierThan(uint256 _time) { assert(now < _time); _; } // ensures that the current time is between _startTime (inclusive) and _endTime (exclusive) modifier between(uint256 _startTime, uint256 _endTime) { assert(now >= _startTime && now < _endTime); _; } // ensures that we didn't reach the soft ether cap, and sets the end time time when we do. Must be placed before the etherCapNotReached. modifier etherSoftCapNotReached(uint256 _contribution) { if (safeAdd(totalEtherContributed, _contribution) >= TOTAL_ETHER_SOFT_CAP) { endTime = now + SOFTCAP_GRACE_DURATION; } _; } // ensures that we didn't reach the ether cap modifier etherCapNotReached(uint256 _contribution) { assert(safeAdd(totalEtherContributed, _contribution) <= TOTAL_ETHER_CAP); _; } // verifies that the presale contribution is more than presale minimum modifier validatePresaleMinPrice() { require(msg.value >= PRESALE_MIN_CONTRIBUTION); _; } // verifies that the presale contribution is from predefined address - TBD (not in use unless we decide to make a whitelist.) modifier validatePresaleAddress() { require(whiteList[msg.sender] == true); _; } // verifies that the total contributions from contributing account do not reach max alloewed unless it is on the whitelist. modifier maxAccountContributionNotReached() { assert(safeAdd(msg.value, safeMul(token.balanceOf(msg.sender), TOKEN_PRICE_N) / TOKEN_PRICE_D) <= MAX_CONTRIBUTION || whiteList[msg.sender]==true); _; } /** @dev computes the number of tokens that should be issued for a given contribution @param _contribution contribution amount @return computed number of tokens */ function computeReturn(uint256 _contribution) public constant returns (uint256) { // return safeMul(_contribution, TOKEN_PRICE_D) / TOKEN_PRICE_N; return safeMul(_contribution, TOKEN_PRICE_D) / TOKEN_PRICE_N; } /** @dev updates the number of contributors */ function upadateContributorsCount(uint256 _tokenAmount) private { if (token.balanceOf(msg.sender) == _tokenAmount ) numOfContributors++; } /** @dev adds a whitelist address for which there is no max contribution and is alloewed to participate in the presale. @param _address verified contributor address @return true */ function addToWhitelist(address _address) public managerOnly returns (bool added) { whiteList[_address] = true; return true; } /** @dev disables an existing whitelist address from participating presale. @param _address verified contributor address to be removed @return true */ function removeFromWhitelist(address _address) public managerOnly returns (bool added) { whiteList[_address] = false; return true; } /** @dev ETH contribution can only be called during the crowdsale @return tokens issued in return */ function contributeETH() public payable between(startTime, endTime) whenNotPaused maxAccountContributionNotReached returns (uint256 amount) { return processContribution(); } /** @dev handles contribution during presale (min 200 ether) can only be called 14 days before the crowdsale start date @return tokens issued in return */ function contributePreSale() public payable between(safeSub(startTime,PRESALE_DURATION), startTime) whenNotPaused validatePresaleMinPrice validatePresaleAddress returns (uint256 amount) { return processContribution(); } /** @dev handles contribution with Fiat - for can only be called by manager @return tokens issued in return */ function contributeFiat(address _contributor, uint256 _amount) public payable managerOnly between(safeSub(startTime,PRESALE_DURATION), safeAdd(startTime, DURATION)) whenNotPaused returns (uint256 amount) { uint256 tokenAmount = computeReturn(_amount); totalEtherContributed = safeAdd(totalEtherContributed, _amount); // update the total contribution amount token.issue(_contributor, tokenAmount); // issue new funds to the contributor's address, provided by the manager, in the smart token token.issue(beneficiary, tokenAmount); // issue tokens to the beneficiary Contribution(_contributor, msg.value, tokenAmount); return tokenAmount; } /** @dev handles contribution logic note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor @return tokens issued in return */ function processContribution() private active etherSoftCapNotReached(msg.value) etherCapNotReached(msg.value) validGasPrice returns (uint256 amount) { uint256 tokenAmount = computeReturn(msg.value); assert(beneficiary.send(msg.value)); // transfer the ether to the beneficiary account totalEtherContributed = safeAdd(totalEtherContributed, msg.value); // update the total contribution amount token.issue(msg.sender, tokenAmount); // issue new funds to the contributor in the smart token token.issue(beneficiary, tokenAmount); // issue tokens to the beneficiary upadateContributorsCount(tokenAmount); Contribution(msg.sender, msg.value, tokenAmount); return tokenAmount; } // fallback function() payable { contributeETH(); } }
/Presale constantsToken constantsState variables triggered on each contribution
contract CrowdsaleController is SmartTokenController, Managed, Pausable { event Contribution(address indexed _contributor, uint256 _amount, uint256 _return); @dev constructor @param _startTime crowdsale start time @param _beneficiary address to receive all ether contributions function CrowdsaleController(uint256 _startTime, address _beneficiary) SmartTokenController(new SmartToken(TOKEN_NAME, TOKEN_SYM, TOKEN_DEC)) validAddress(_beneficiary) earlierThan(_startTime) { startTime = _startTime; endTime = startTime + DURATION; beneficiary = _beneficiary; token.disableTransfers(true); } modifier validGasPrice() { assert(tx.gasprice <= MAX_GAS_PRICE); _; } modifier earlierThan(uint256 _time) { assert(now < _time); _; } modifier between(uint256 _startTime, uint256 _endTime) { assert(now >= _startTime && now < _endTime); _; } modifier etherSoftCapNotReached(uint256 _contribution) { if (safeAdd(totalEtherContributed, _contribution) >= TOTAL_ETHER_SOFT_CAP) { endTime = now + SOFTCAP_GRACE_DURATION; } _; } modifier etherSoftCapNotReached(uint256 _contribution) { if (safeAdd(totalEtherContributed, _contribution) >= TOTAL_ETHER_SOFT_CAP) { endTime = now + SOFTCAP_GRACE_DURATION; } _; } modifier etherCapNotReached(uint256 _contribution) { assert(safeAdd(totalEtherContributed, _contribution) <= TOTAL_ETHER_CAP); _; } modifier validatePresaleMinPrice() { require(msg.value >= PRESALE_MIN_CONTRIBUTION); _; } modifier validatePresaleAddress() { require(whiteList[msg.sender] == true); _; } modifier maxAccountContributionNotReached() { assert(safeAdd(msg.value, safeMul(token.balanceOf(msg.sender), TOKEN_PRICE_N) / TOKEN_PRICE_D) <= MAX_CONTRIBUTION || whiteList[msg.sender]==true); _; } @param _contribution contribution amount @return computed number of tokens @dev computes the number of tokens that should be issued for a given contribution function computeReturn(uint256 _contribution) public constant returns (uint256) { return safeMul(_contribution, TOKEN_PRICE_D) / TOKEN_PRICE_N; } @dev updates the number of contributors function upadateContributorsCount(uint256 _tokenAmount) private { if (token.balanceOf(msg.sender) == _tokenAmount ) numOfContributors++; } @param _address verified contributor address @return true @dev adds a whitelist address for which there is no max contribution and is alloewed to participate in the presale. function addToWhitelist(address _address) public managerOnly returns (bool added) { whiteList[_address] = true; return true; } @param _address verified contributor address to be removed @return true @dev disables an existing whitelist address from participating presale. function removeFromWhitelist(address _address) public managerOnly returns (bool added) { whiteList[_address] = false; return true; } can only be called during the crowdsale @return tokens issued in return @dev ETH contribution function contributeETH() public payable between(startTime, endTime) whenNotPaused maxAccountContributionNotReached returns (uint256 amount) { return processContribution(); } can only be called 14 days before the crowdsale start date @return tokens issued in return @dev handles contribution during presale (min 200 ether) function contributePreSale() public payable between(safeSub(startTime,PRESALE_DURATION), startTime) whenNotPaused validatePresaleMinPrice validatePresaleAddress returns (uint256 amount) { return processContribution(); } can only be called by manager @return tokens issued in return @dev handles contribution with Fiat - for function contributeFiat(address _contributor, uint256 _amount) public payable managerOnly between(safeSub(startTime,PRESALE_DURATION), safeAdd(startTime, DURATION)) whenNotPaused returns (uint256 amount) { uint256 tokenAmount = computeReturn(_amount); Contribution(_contributor, msg.value, tokenAmount); return tokenAmount; } note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor @return tokens issued in return @dev handles contribution logic function processContribution() private active etherSoftCapNotReached(msg.value) etherCapNotReached(msg.value) validGasPrice returns (uint256 amount) { uint256 tokenAmount = computeReturn(msg.value); upadateContributorsCount(tokenAmount); Contribution(msg.sender, msg.value, tokenAmount); return tokenAmount; } function() payable { contributeETH(); } }
12,909,607
[ 1, 19, 12236, 5349, 6810, 1345, 6810, 1119, 3152, 10861, 603, 1517, 24880, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 385, 492, 2377, 5349, 2933, 353, 19656, 1345, 2933, 16, 10024, 16, 21800, 16665, 288, 203, 203, 377, 203, 203, 377, 203, 377, 203, 377, 203, 377, 203, 1377, 203, 203, 565, 871, 735, 4027, 12, 2867, 8808, 389, 591, 19293, 16, 2254, 5034, 389, 8949, 16, 2254, 5034, 389, 2463, 1769, 203, 203, 3639, 632, 5206, 3885, 203, 3639, 632, 891, 389, 1937, 950, 1377, 276, 492, 2377, 5349, 787, 813, 203, 3639, 632, 891, 389, 70, 4009, 74, 14463, 814, 565, 1758, 358, 6798, 777, 225, 2437, 13608, 6170, 203, 565, 445, 385, 492, 2377, 5349, 2933, 12, 11890, 5034, 389, 1937, 950, 16, 1758, 389, 70, 4009, 74, 14463, 814, 13, 203, 3639, 19656, 1345, 2933, 12, 2704, 19656, 1345, 12, 8412, 67, 1985, 16, 14275, 67, 7474, 49, 16, 14275, 67, 1639, 39, 3719, 203, 3639, 923, 1887, 24899, 70, 4009, 74, 14463, 814, 13, 203, 3639, 13805, 9516, 24899, 1937, 950, 13, 203, 203, 203, 565, 288, 203, 3639, 8657, 273, 389, 1937, 950, 31, 203, 3639, 13859, 273, 8657, 397, 31794, 31, 203, 3639, 27641, 74, 14463, 814, 273, 389, 70, 4009, 74, 14463, 814, 31, 203, 3639, 1147, 18, 8394, 1429, 18881, 12, 3767, 1769, 203, 565, 289, 203, 203, 565, 9606, 923, 27998, 5147, 1435, 288, 203, 3639, 1815, 12, 978, 18, 31604, 8694, 1648, 4552, 67, 43, 3033, 67, 7698, 1441, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 13805, 9516, 12, 11890, 5034, 389, 957, 13, 288, 203, 3639, 2 ]
pragma solidity 0.6.6; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ICheckpointManager} from "./interfaces/ICheckpointManager.sol"; import {RLPReader} from "./libraries/RLPReader.sol"; import {MerklePatriciaProof} from "./libraries/MerklePatriciaProof.sol"; import {Merkle} from "./libraries/Merkle.sol"; contract ProofVerifier { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using SafeMath for uint256; ICheckpointManager internal _checkpointManager; /** * @param checkpointManager address of checkpoint manager contract */ constructor(address checkpointManager) public { _checkpointManager = ICheckpointManager(checkpointManager); } /** * @notice exit tokens by providing proof * @dev This function verifies if the transaction actually happened on child chain * the transaction log is then sent to token predicate to handle it accordingly * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function exit(bytes calldata inputData) view external returns (bool) { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); // branch mask can be maximum 32 bits require( inputDataRLPList[8].toUint() & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 == 0, "RootChainManager: INVALID_BRANCH_MASK" ); // verify receipt inclusion require( MerklePatriciaProof.verify( inputDataRLPList[6].toBytes(), // receipt inputDataRLPList[8].toBytes(), // branchMask inputDataRLPList[7].toBytes(), // receiptProof bytes32(inputDataRLPList[5].toUint()) // receiptRoot ), "RootChainManager: INVALID_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( inputDataRLPList[2].toUint(), // blockNumber inputDataRLPList[3].toUint(), // blockTime bytes32(inputDataRLPList[4].toUint()), // txRoot bytes32(inputDataRLPList[5].toUint()), // receiptRoot inputDataRLPList[0].toUint(), // headerNumber inputDataRLPList[1].toBytes() // blockProof ); return true; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = _checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber.sub(startBlock), headerRoot, blockProof ), "RootChainManager: INVALID_HEADER" ); return createdAt; } }
* @notice exit tokens by providing proof @dev This function verifies if the transaction actually happened on child chain the transaction log is then sent to token predicate to handle it accordingly @param inputData RLP encoded data of the reference tx containing following list of fields 0 - headerNumber - Checkpoint header block number containing the reference tx 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root 2 - blockNumber - Block number containing the reference tx on child chain 3 - blockTime - Reference tx block time 4 - txRoot - Transactions root of block 5 - receiptRoot - Receipts root of block 6 - receipt - Receipt of the reference transaction 7 - receiptProof - Merkle proof of the reference receipt 8 - branchMask - 32 bits denoting the path of receipt in merkle tree 9 - receiptLogIndex - Log Index to read from the receipt/ branch mask can be maximum 32 bits verify receipt inclusion verify checkpoint inclusion
function exit(bytes calldata inputData) view external returns (bool) { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); require( inputDataRLPList[8].toUint() & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 == 0, "RootChainManager: INVALID_BRANCH_MASK" ); require( MerklePatriciaProof.verify( ), "RootChainManager: INVALID_PROOF" ); _checkBlockMembershipInCheckpoint( ); return true; }
6,397,348
[ 1, 8593, 2430, 635, 17721, 14601, 225, 1220, 445, 20761, 309, 326, 2492, 6013, 17497, 603, 1151, 2687, 326, 2492, 613, 353, 1508, 3271, 358, 1147, 5641, 358, 1640, 518, 15905, 225, 24149, 534, 14461, 3749, 501, 434, 326, 2114, 2229, 4191, 3751, 666, 434, 1466, 225, 374, 300, 1446, 1854, 300, 25569, 1446, 1203, 1300, 4191, 326, 2114, 2229, 225, 404, 300, 1203, 20439, 300, 1186, 792, 716, 326, 1203, 1446, 261, 267, 326, 1151, 2687, 13, 353, 279, 7839, 316, 326, 9638, 30235, 1365, 225, 576, 300, 1203, 1854, 300, 3914, 1300, 4191, 326, 2114, 2229, 603, 1151, 2687, 225, 890, 300, 1203, 950, 300, 6268, 2229, 1203, 813, 225, 1059, 300, 2229, 2375, 300, 27148, 1365, 434, 1203, 225, 1381, 300, 16030, 2375, 300, 9797, 27827, 1365, 434, 1203, 225, 1666, 300, 16030, 300, 29787, 434, 326, 2114, 2492, 225, 2371, 300, 16030, 20439, 300, 31827, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 2427, 12, 3890, 745, 892, 24149, 13, 1476, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 534, 14461, 2514, 18, 54, 48, 1102, 874, 8526, 3778, 24149, 54, 14461, 682, 273, 24149, 203, 5411, 263, 869, 54, 9953, 1180, 1435, 203, 5411, 263, 869, 682, 5621, 203, 203, 3639, 2583, 12, 203, 5411, 24149, 54, 14461, 682, 63, 28, 8009, 869, 5487, 1435, 473, 203, 7734, 374, 6356, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 18343, 12648, 422, 203, 7734, 374, 16, 203, 5411, 315, 2375, 3893, 1318, 30, 10071, 67, 7192, 20360, 67, 11704, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 31827, 22834, 1512, 1155, 20439, 18, 8705, 12, 203, 5411, 262, 16, 203, 5411, 315, 2375, 3893, 1318, 30, 10071, 67, 3373, 3932, 6, 203, 3639, 11272, 203, 203, 3639, 389, 1893, 1768, 13447, 382, 14431, 12, 203, 3639, 11272, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x166Ae04a3fc1c916eE4FBc46F0e90952df7B1EB0/sources/contracts/Sign.sol
maps every hash to the time it was verified
mapping (bytes32 => uint256) public verified;
7,157,688
[ 1, 10711, 3614, 1651, 358, 326, 813, 518, 1703, 13808, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 3890, 1578, 516, 2254, 5034, 13, 1071, 13808, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.8.0; import {AddressIsContract} from "@animoca/ethereum-contracts-core/contracts/utils/types/AddressIsContract.sol"; import {IERC165} from "@animoca/ethereum-contracts-core/contracts/introspection/IERC165.sol"; import {IERC721} from "./interfaces/IERC721.sol"; import {IERC721Events} from "./interfaces/IERC721Events.sol"; import {IERC721Receiver} from "./interfaces/IERC721Receiver.sol"; import {ManagedIdentity} from "@animoca/ethereum-contracts-core/contracts/metatx/ManagedIdentity.sol"; /** * @title ERC721 Non Fungible Token Contract, simple implementation. */ contract ERC721Simple is ManagedIdentity, IERC165, IERC721, IERC721Events { using AddressIsContract for address; bytes4 internal constant _ERC721_RECEIVED = type(IERC721Receiver).interfaceId; uint256 internal constant _APPROVAL_BIT_TOKEN_OWNER_ = 1 << 160; /* owner => operator => approved */ mapping(address => mapping(address => bool)) internal _operators; /* NFT ID => owner */ mapping(uint256 => uint256) internal _owners; /* owner => NFT balance */ mapping(address => uint256) internal _nftBalances; /* NFT ID => operator */ mapping(uint256 => address) internal _nftApprovals; //======================================================= ERC165 ========================================================// /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC721).interfaceId; } //======================================================= ERC721 ========================================================// /// @inheritdoc IERC721 function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: zero address"); return _nftBalances[owner]; } /// @inheritdoc IERC721 function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = address(uint160(_owners[tokenId])); require(owner != address(0), "ERC721: non-existing NFT"); return owner; } /// @inheritdoc IERC721 function approve(address to, uint256 tokenId) public virtual override { uint256 owner = _owners[tokenId]; require(owner != 0, "ERC721: non-existing NFT"); address ownerAddress = address(uint160(owner)); require(to != ownerAddress, "ERC721: self-approval"); require(_isOperatable(ownerAddress, _msgSender()), "ERC721: non-approved sender"); if (to == address(0)) { if (owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) { // remove the approval bit if it is present _owners[tokenId] = uint256(ownerAddress); } } else { uint256 ownerWithApprovalBit = owner | _APPROVAL_BIT_TOKEN_OWNER_; if (owner != ownerWithApprovalBit) { // add the approval bit if it is not present _owners[tokenId] = ownerWithApprovalBit; } _nftApprovals[tokenId] = to; } emit Approval(ownerAddress, to, tokenId); } /// @inheritdoc IERC721 function getApproved(uint256 tokenId) public view virtual override returns (address) { uint256 owner = _owners[tokenId]; require(address(uint160(owner)) != address(0), "ERC721: non-existing NFT"); if (owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) { return _nftApprovals[tokenId]; } else { return address(0); } } /// @inheritdoc IERC721 function setApprovalForAll(address operator, bool approved) public virtual override { address sender = _msgSender(); require(operator != sender, "ERC721: self-approval"); _operators[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /// @inheritdoc IERC721 function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operators[owner][operator]; } /// @inheritdoc IERC721 function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transferFrom( from, to, tokenId, "", /* safe */ false ); } /// @inheritdoc IERC721 function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { _transferFrom( from, to, tokenId, "", /* safe */ true ); } /// @inheritdoc IERC721 function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public virtual override { _transferFrom( from, to, tokenId, data, /* safe */ true ); } //============================================ High-level Internal Functions ============================================// function _transferFrom( address from, address to, uint256 tokenId, bytes memory data, bool safe ) internal virtual { require(to != address(0), "ERC721: transfer to zero"); address sender = _msgSender(); bool operatable = _isOperatable(from, sender); uint256 owner = _owners[tokenId]; require(from == address(uint160(owner)), "ERC721: non-owned NFT"); if (!operatable) { require((owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) && _msgSender() == _nftApprovals[tokenId], "ERC721: non-approved sender"); } _owners[tokenId] = uint256(uint160(to)); if (from != to) { // cannot underflow as balance is verified through ownership --_nftBalances[from]; // cannot overflow as supply cannot overflow ++_nftBalances[to]; } emit Transfer(from, to, tokenId); if (safe && to.isContract()) { require(IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) == _ERC721_RECEIVED, "ERC721: transfer refused"); } } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to zero"); require(_owners[tokenId] == 0, "ERC721: existing NFT"); _owners[tokenId] = uint256(uint160(to)); // cannot overflow due to the cost of minting individual tokens ++_nftBalances[to]; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = address(uint160(_owners[tokenId])); require(owner != address(0), "ERC721: non-existing NFT"); _owners[tokenId] = 0; // cannot underflow as balance is verified through NFT ownership --_nftBalances[owner]; emit Transfer(owner, address(0), tokenId); } //============================================== Internal Helper Functions ==============================================// /** * Returns whether `sender` is authorised to make a transfer on behalf of `from`. * @param from The address to check operatibility upon. * @param sender The sender address. * @return True if sender is `from` or an operator for `from`, false otherwise. */ function _isOperatable(address from, address sender) internal view returns (bool) { return (from == sender) || _operators[from][sender]; } }
cannot overflow due to the cost of minting individual tokens
function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to zero"); require(_owners[tokenId] == 0, "ERC721: existing NFT"); _owners[tokenId] = uint256(uint160(to)); ++_nftBalances[to]; emit Transfer(address(0), to, tokenId); }
6,348,206
[ 1, 12892, 9391, 6541, 358, 326, 6991, 434, 312, 474, 310, 7327, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 389, 81, 474, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 312, 474, 358, 3634, 8863, 203, 3639, 2583, 24899, 995, 414, 63, 2316, 548, 65, 422, 374, 16, 315, 654, 39, 27, 5340, 30, 2062, 423, 4464, 8863, 203, 203, 3639, 389, 995, 414, 63, 2316, 548, 65, 273, 2254, 5034, 12, 11890, 16874, 12, 869, 10019, 203, 203, 3639, 965, 67, 82, 1222, 38, 26488, 63, 869, 15533, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xDD7E62725f586166995d048e797E6D05413B2D70/sources/contracts/protocol/markets/basic/library/MarketLib.sol
@notice Returns the maximum value(power) available for verification for side @param m Market info @param side Side of market (true/false) @return 0 Maximum amount to verify for side
function maxAmountToVerifyForSide(Market memory m, bool side) external pure returns (uint256) { return (_maxAmountToVerifyForSide(m, side)); }
837,621
[ 1, 1356, 326, 4207, 460, 12, 12238, 13, 2319, 364, 11805, 364, 4889, 225, 312, 6622, 278, 1123, 225, 4889, 26248, 434, 13667, 261, 3767, 19, 5743, 13, 327, 374, 18848, 3844, 358, 3929, 364, 4889, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 943, 6275, 774, 8097, 1290, 8895, 12, 3882, 278, 3778, 312, 16, 1426, 4889, 13, 203, 3639, 3903, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 261, 67, 1896, 6275, 774, 8097, 1290, 8895, 12, 81, 16, 4889, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import { SafeMath } from '@openzeppelin/contracts/math/SafeMath.sol'; import { IERC20 } from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import { IAction } from '../interfaces/IAction.sol'; import "hardhat/console.sol"; /** * Error Codes * O1: actions for the vault have not been initialized * O2: cannot execute transaction, vault is in emergency state * O3: cannot call setActions, actions have already been initialized * O4: action being set is using an invalid address * O5: action being set is a duplicated action * O6: deposited underlying (msg.value) must be greater than 0 * O7: cannot accept underlying deposit, total underlying controlled by the vault would exceed vault cap * O8: unable to withdraw underlying, underlying to withdraw would exceed or be equal to the current vault underlying balance * O9: unable to withdraw underlying, underlying fee transfer to fee recipient (feeRecipient) failed * O10: unable to withdraw underlying, underlying withdrawal to user (msg.sender) failed * O11: cannot close vault positions, vault is not in locked state (VaultState.Locked) * O12: unable to rollover vault, length of allocation percentages (_allocationPercentages) passed is not equal to the initialized actions length * O13: unable to rollover vault, vault is not in unlocked state (VaultState.Unlocked) * O14: unable to rollover vault, the calculated percentage sum (sumPercentage) is greater than the base (BASE) * O15: unable to rollover vault, the calculated percentage sum (sumPercentage) is not equal to the base (BASE) * O16: withdraw reserve percentage must be less than 50% (5000) * O17: cannot call emergencyPause, vault is already in emergency state * O18: cannot call resumeFromPause, vault is not in emergency state * O19: cannot accept underlying deposit, accounting before and after deposit does not match * O20: unable to withdraw underlying, accounting before and after withdrawal does not match */ /** * @title OpynPerpVault * @author Opyn Team * @dev implementation of the Opyn Perp Vault contract for covered calls using as collateral the underlying. */ contract OpynPerpVault is ERC20, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; enum VaultState { Emergency, Locked, Unlocked } /// @dev actions that build up this strategy (vault) address[] public actions; /// @dev address to which all withdrawal fees are sent address public feeWithdrawalRecipient; /// @dev address to which all performance fees are sent address public feePerformanceRecipient; /// @dev address of the underlying address address public underlying; uint256 public constant BASE = 10000; // 100% /// @dev Cap for the vault. hardcoded at 1000 for initial release uint256 public cap = 1000 ether; /// @dev withdrawal fee percentage. 50 being 0.5% uint256 public withdrawalFeePercentage = 50; /// @dev what percentage should be reserved in vault for withdraw. 1000 being 10% uint256 public withdrawReserve = 0; /// @dev performance fee percentage. 1000 being 10% uint256 public performanceFeePercentage = 1000; VaultState public state; VaultState public stateBeforePause; /*===================== * Events * *====================*/ event CapUpdated(uint256 newCap); event Deposit(address account, uint256 amountDeposited, uint256 shareMinted); event Rollover(uint256[] allocations); event StateUpdated(VaultState state); event FeeSent(uint256 amount, address feeRecipient); event Withdraw(address account, uint256 amountWithdrawn, uint256 shareBurned); /*===================== * Modifiers * *====================*/ /** * @dev can only be called if actions are initialized */ function actionsInitialized() private view { require(actions.length > 0, "O1"); } /** * @dev can only be executed if vault is not in emergency state */ function notEmergency() private view { require(state != VaultState.Emergency, "O2"); } /*===================== * external function * *====================*/ constructor ( address _underlying, address _feeWithdrawalRecipient, address _feePerformanceRecipient, string memory _tokenName, string memory _tokenSymbol ) ERC20(_tokenName, _tokenSymbol) { underlying = _underlying; feeWithdrawalRecipient = _feeWithdrawalRecipient; feePerformanceRecipient = _feePerformanceRecipient; state = VaultState.Unlocked; } function setActions(address[] memory _actions) external onlyOwner { require(actions.length == 0, "O3"); // assign actions for(uint256 i = 0 ; i < _actions.length; i++ ) { // check all items before actions[i], does not equal to action[i] require(_actions[i] != address(0), "O4"); for(uint256 j = 0; j < i; j++) { require(_actions[i] != _actions[j], "O5"); } actions.push(_actions[i]); } } /** * @notice allows owner to change the cap */ function setCap(uint256 _newCap) external onlyOwner { cap = _newCap; emit CapUpdated(_newCap); } /** * @notice total underlying controlled by this vault */ function totalUnderlyingAsset() public view returns (uint256) { uint256 debt = 0; uint256 length = actions.length; for (uint256 i = 0; i < length; i++) { debt = debt.add(IAction(actions[i]).currentValue()); } return _balance().add(debt); } /** * @dev return how much underlying you can get if you burn the number of shares, after charging the withdrawal fee. */ function getWithdrawAmountByShares(uint256 _shares) external view returns (uint256) { uint256 withdrawAmount = _getWithdrawAmountByShares(_shares); return withdrawAmount.sub(_getWithdrawFee(withdrawAmount)); } /** * @notice deposits underlying into the contract and mints vault shares. * @dev deposit into the contract, then mint the shares to depositor, and emit the deposit event * @param amount amount of underlying to deposit */ function depositUnderlying(uint256 amount) external nonReentrant { notEmergency(); actionsInitialized(); require(amount > 0, 'O6'); // keep track of underlying balance before uint256 totalUnderlyingBeforeDeposit = totalUnderlyingAsset(); // deposit underlying to vault IERC20 underlyingToken = IERC20(underlying); underlyingToken.safeTransferFrom(msg.sender, address(this), amount); // keep track of underlying balance after uint256 totalUnderlyingAfterDeposit = totalUnderlyingAsset(); require(totalUnderlyingAfterDeposit < cap, 'O7'); require(totalUnderlyingAfterDeposit.sub(totalUnderlyingBeforeDeposit) == amount, 'O19'); // mint shares and emit event uint256 share = _getSharesByDepositAmount(amount, totalUnderlyingBeforeDeposit); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); } /** * @notice withdraws underlying from vault using vault shares * @dev burns shares, sends underlying to user, sends withdrawal fee to withdrawal fee recepient * @param _share is the number of vault shares to be burned */ function withdrawUnderlying(uint256 _share) external nonReentrant { notEmergency(); actionsInitialized(); // keep track of underlying balance before IERC20 underlyingToken = IERC20(underlying); uint256 totalUnderlyingBeforeWithdrawal = totalUnderlyingAsset(); // withdraw underlying from vault uint256 underlyingToRecipientBeforeFees = _getWithdrawAmountByShares(_share); uint256 fee = _getWithdrawFee(underlyingToRecipientBeforeFees); uint256 underlyingToRecipientAfterFees = underlyingToRecipientBeforeFees.sub(fee); require(underlyingToRecipientBeforeFees <= _balance(), 'O8'); // burn shares _burn(msg.sender, _share); // transfer withdrawal fee to recipient underlyingToken.safeTransfer(feeWithdrawalRecipient, fee); emit FeeSent(fee, feeWithdrawalRecipient); // send underlying to user underlyingToken.safeTransfer(msg.sender, underlyingToRecipientAfterFees); // keep track of underlying balance after uint256 totalUnderlyingAfterWithdrawal = totalUnderlyingAsset(); require(totalUnderlyingBeforeWithdrawal.sub(totalUnderlyingAfterWithdrawal) == underlyingToRecipientBeforeFees, 'O20'); emit Withdraw(msg.sender, underlyingToRecipientAfterFees, _share); } /** * @notice anyone can call this to close out the previous round by calling "closePositions" on all actions. * @notice can only be called when the vault is locked. It sets the state to unlocked and brings funds from each action to the vault. * @dev iterrate through each action, close position and withdraw funds */ function closePositions() public { actionsInitialized(); require(state == VaultState.Locked, "O11"); state = VaultState.Unlocked; address cacheAddress = underlying; address[] memory cacheActions = actions; for (uint256 i = 0; i < cacheActions.length; i = i + 1) { // asset amount used in minting options for cycle uint256 lockedAsset = IAction(cacheActions[i]).currentLockedAsset(); // 1. close position. this should revert if any position is not ready to be closed. IAction(cacheActions[i]).closePosition(); // 2. withdraw underlying from the action uint256 actionBalance = IERC20(cacheAddress).balanceOf(cacheActions[i]); uint256 netActionBalance; if (actionBalance > 0){ netActionBalance = actionBalance; // check if performance fee applies and strategy was profitable if(performanceFeePercentage > 0 && actionBalance > lockedAsset){ // get profit uint256 profit = actionBalance.sub(lockedAsset); uint256 performanceFee = _getPerformanceFee(profit); // transfer performance fee IERC20(cacheAddress).safeTransferFrom(cacheActions[i], feePerformanceRecipient, performanceFee); emit FeeSent(performanceFee, feePerformanceRecipient); // update action net balance netActionBalance = actionBalance.sub(performanceFee); } // underlying back to vault IERC20(cacheAddress).safeTransferFrom(cacheActions[i], address(this), netActionBalance); } } emit StateUpdated(VaultState.Unlocked); } /** * @notice can only be called when the vault is unlocked. It sets the state to locked and distributes funds to each action. */ function rollOver(uint256[] calldata _allocationPercentages) external onlyOwner nonReentrant { actionsInitialized(); require(_allocationPercentages.length == actions.length, 'O12'); require(state == VaultState.Unlocked, "O13"); state = VaultState.Locked; address cacheAddress = underlying; address[] memory cacheActions = actions; uint256 cacheBase = BASE; uint256 cacheTotalAsset = totalUnderlyingAsset(); // keep track of total percentage to make sure we're summing up to 100% uint256 sumPercentage = withdrawReserve; for (uint256 i = 0; i < _allocationPercentages.length; i = i + 1) { sumPercentage = sumPercentage.add(_allocationPercentages[i]); require(sumPercentage <= cacheBase, 'O14'); uint256 newAmount = cacheTotalAsset.mul(_allocationPercentages[i]).div(cacheBase); if (newAmount > 0) IERC20(cacheAddress).safeTransfer(cacheActions[i], newAmount); IAction(cacheActions[i]).rolloverPosition(); } require(sumPercentage == cacheBase, 'O15'); emit Rollover(_allocationPercentages); emit StateUpdated(VaultState.Locked); } /** * @dev set the vault withdrawal fee recipient */ function setWithdrawalFeeRecipient(address _newWithdrawalFeeRecipient) external onlyOwner { feeWithdrawalRecipient = _newWithdrawalFeeRecipient; } /** * @dev set the vault performance fee recipient */ function setPerformanceFeeRecipient(address _newPerformanceFeeRecipient) external onlyOwner { feePerformanceRecipient = _newPerformanceFeeRecipient; } /** * @dev set the vault fee recipient - use when performance fee and withdrawal fee is sent to the same recipient */ function setFeeRecipient(address _newFeeRecipient) external onlyOwner { feeWithdrawalRecipient = _newFeeRecipient; feePerformanceRecipient = _newFeeRecipient; } /** * @dev set the percentage fee that should be applied upon withdrawal */ function setWithdrawalFeePercentage(uint256 _newWithdrawalFeePercentage) external onlyOwner { withdrawalFeePercentage = _newWithdrawalFeePercentage; } /** * @dev set the percentage fee that should be applied on profits at the end of cycles */ function setPerformanceFeePercentage(uint256 _newPerformanceFeePercentage) external onlyOwner { performanceFeePercentage = _newPerformanceFeePercentage; } /** * @dev set the percentage that should be reserved in vault for withdraw */ function setWithdrawReserve(uint256 _reserve) external onlyOwner { require(_reserve < 5000, "O16"); withdrawReserve = _reserve; } /** * @dev set the state to "Emergency", which disable all withdraw and deposit */ function emergencyPause() external onlyOwner { require(state != VaultState.Emergency, "O17"); stateBeforePause = state; state = VaultState.Emergency; emit StateUpdated(VaultState.Emergency); } /** * @dev set the state from "Emergency", which disable all withdraw and deposit */ function resumeFromPause() external onlyOwner { require(state == VaultState.Emergency, "O18"); state = stateBeforePause; emit StateUpdated(stateBeforePause); } /** * @dev return how many shares you can get if you deposit {_amount} underlying * @param _amount amount of token depositing */ function getSharesByDepositAmount(uint256 _amount) external view returns (uint256) { return _getSharesByDepositAmount(_amount, totalUnderlyingAsset()); } /*===================== * Internal functions * *====================*/ /** * @dev returns remaining underlying balance in the vault. */ function _balance() internal view returns (uint256) { return IERC20(underlying).balanceOf(address(this)); } /** * @dev return how many shares you can get if you deposit {_amount} underlying * @param _amount amount of underlying depositing * @param _totalAssetAmount amount of underlying already in the pool before deposit */ function _getSharesByDepositAmount(uint256 _amount, uint256 _totalAssetAmount) internal view returns (uint256) { uint256 shareSupply = totalSupply(); // share amount return shareSupply == 0 ? _amount : _amount.mul(shareSupply).div(_totalAssetAmount); } /** * @dev return how much underlying you can get if you burn the number of shares */ function _getWithdrawAmountByShares(uint256 _share) internal view returns (uint256) { // withdrawal amount return _share.mul(totalUnderlyingAsset()).div(totalSupply()); } /** * @dev get amount of fee charged based on total amount of underlying withdrawing. */ function _getWithdrawFee(uint256 _withdrawAmount) internal view returns (uint256) { return _withdrawAmount.mul(withdrawalFeePercentage).div(BASE); } /** * @dev get amount of fee charged based on total profit amount earned in a cycle. */ function _getPerformanceFee(uint256 _profitAmount) internal view returns (uint256) { return _profitAmount.mul(performanceFeePercentage).div(BASE); } } // 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; 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 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 arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.2; interface IAction { /** * The function used to determin how much asset the current action is controlling. * this will impact the withdraw and deposit amount calculated from the vault. */ function currentValue() external view returns (uint256); /** * The function for the vault to call at the end of each vault's round. * after calling this function, the vault will try to pull assets back from the action and enable withdraw. */ function closePosition() external; /** * The function for the vault to call when the vault is ready to start the next round. * the vault will push assets to action before calling this function, but the amount can change compare to * the last round. So each action should check their asset balance instead of using any cached balance. * * Each action can also add additional checks and revert the `rolloverPosition` call if the action * is not ready to go into the next round. */ function rolloverPosition() external; /** * The function used to determine how much asset is locked in the current action. * this will impact the closeposition amount calculated from the vault. */ function currentLockedAsset() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @dev get amount of fee charged based on total amount of underlying withdrawing./
function _getWithdrawFee(uint256 _withdrawAmount) internal view returns (uint256) { return _withdrawAmount.mul(withdrawalFeePercentage).div(BASE); }
1,583,021
[ 1, 588, 3844, 434, 14036, 1149, 2423, 2511, 603, 2078, 3844, 434, 6808, 598, 9446, 310, 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, 225, 445, 389, 588, 1190, 9446, 14667, 12, 11890, 5034, 389, 1918, 9446, 6275, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 1918, 9446, 6275, 18, 16411, 12, 1918, 9446, 287, 14667, 16397, 2934, 2892, 12, 8369, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "@keep-network/keep-core/contracts/PhasedEscrow.sol"; import "./ECDSARewardsDistributor.sol"; /// @title ECDSARewardsDistributorEscrow /// @notice A token holder contract allowing contract owner to allocate rewards /// to ECDSARewardsDistributor in phases. Each phase corresponds to /// a new reward interval allocated with its own merkle root used by /// stakers to withdraw their rewards. contract ECDSARewardsDistributorEscrow is PhasedEscrow { ECDSARewardsDistributor public ecdsaRewardsDistributor; constructor(IERC20 _token, ECDSARewardsDistributor _ecdsaRewardsDistributor) public PhasedEscrow(_token) { ecdsaRewardsDistributor = _ecdsaRewardsDistributor; } function allocateInterval(bytes32 merkleRoot, uint256 amount) external onlyOwner { token.approve(address(ecdsaRewardsDistributor), amount); ecdsaRewardsDistributor.allocate(merkleRoot, amount); } }
@title ECDSARewardsDistributorEscrow @notice A token holder contract allowing contract owner to allocate rewards to ECDSARewardsDistributor in phases. Each phase corresponds to a new reward interval allocated with its own merkle root used by stakers to withdraw their rewards.
contract ECDSARewardsDistributorEscrow is PhasedEscrow { ECDSARewardsDistributor public ecdsaRewardsDistributor; constructor(IERC20 _token, ECDSARewardsDistributor _ecdsaRewardsDistributor) public PhasedEscrow(_token) ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ { ecdsaRewardsDistributor = _ecdsaRewardsDistributor; } function allocateInterval(bytes32 merkleRoot, uint256 amount) external onlyOwner { token.approve(address(ecdsaRewardsDistributor), amount); ecdsaRewardsDistributor.allocate(merkleRoot, amount); } }
12,598,144
[ 1, 7228, 3948, 985, 359, 14727, 1669, 19293, 6412, 492, 225, 432, 1147, 10438, 6835, 15632, 6835, 3410, 358, 10101, 283, 6397, 540, 358, 7773, 3948, 985, 359, 14727, 1669, 19293, 316, 24642, 18, 8315, 6855, 13955, 358, 540, 279, 394, 19890, 3673, 11977, 598, 2097, 4953, 30235, 1365, 1399, 635, 540, 384, 581, 414, 358, 598, 9446, 3675, 283, 6397, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 7773, 3948, 985, 359, 14727, 1669, 19293, 6412, 492, 353, 4360, 8905, 6412, 492, 288, 203, 565, 7773, 3948, 985, 359, 14727, 1669, 19293, 1071, 23593, 17631, 14727, 1669, 19293, 31, 203, 203, 565, 3885, 12, 45, 654, 39, 3462, 389, 2316, 16, 7773, 3948, 985, 359, 14727, 1669, 19293, 389, 557, 19603, 17631, 14727, 1669, 19293, 13, 203, 3639, 1071, 203, 3639, 4360, 8905, 6412, 492, 24899, 2316, 13, 203, 163, 249, 246, 163, 249, 246, 163, 249, 239, 225, 163, 249, 246, 163, 249, 246, 225, 163, 249, 243, 163, 249, 246, 163, 249, 246, 225, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 239, 163, 249, 243, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 225, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 163, 249, 246, 225, 163, 249, 246, 163, 249, 246, 163, 249, 246, 2 ]
./partial_match/1/0x8223e8AF7250E15d542D096FF6A59d7880186D84/sources/SwapUSDTdUSD.sol
transfer DAI to pool Mint dUSD
function MintdUSD(uint256 _amount) external { require(_amount > 0, "need gt 0"); depositAt[msg.sender] = block.number; token.safeTransferFrom(msg.sender, address(this), _amount); uint256 amountTransfer = _amount.mul(uint256(1e18)).div(10**dUSDDecimal); pooldUSD.mint(msg.sender, amountTransfer); emit TokenSwap( msg.sender, _amount, "Swap USDT to dUSD", block.timestamp ); }
3,961,800
[ 1, 13866, 463, 18194, 358, 2845, 490, 474, 302, 3378, 40, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 490, 474, 72, 3378, 40, 12, 11890, 5034, 389, 8949, 13, 3903, 288, 203, 202, 202, 6528, 24899, 8949, 405, 374, 16, 315, 14891, 9879, 374, 8863, 203, 3639, 443, 1724, 861, 63, 3576, 18, 15330, 65, 273, 1203, 18, 2696, 31, 203, 3639, 1147, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 2254, 5034, 3844, 5912, 273, 389, 8949, 18, 16411, 12, 11890, 5034, 12, 21, 73, 2643, 13, 2934, 2892, 12, 2163, 636, 72, 3378, 40, 5749, 1769, 203, 3639, 2845, 72, 3378, 40, 18, 81, 474, 12, 3576, 18, 15330, 16, 3844, 5912, 1769, 203, 203, 3639, 3626, 3155, 12521, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 8949, 16, 203, 5411, 315, 12521, 11836, 9081, 358, 302, 3378, 40, 3113, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 202, 97, 203, 7010, 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 ]
pragma solidity >=0.6.0; // AbiHeader section allows to define which fields are expected to be in the header of inbound message. // This fields must be read in the replay protection function. pragma AbiHeader time; pragma AbiHeader expire; // This contract demonstrates custom replay protection functionality. contract CustomReplaySample { // Each transaction is limited by gas, so we must limit count of iteration in loop. uint8 constant MAX_CLEANUP_MSGS = 30; // mapping to store hashes of inbound messages; mapping(uint => uint32) messages; // dummy variable to demonstrate contract functionality. uint public value; constructor() public { // check that contract's public key is set require(tvm.pubkey() != 0, 101); // Check that message has signature (msg.pubkey() is not zero) and message is signed with the owner's private key require(msg.pubkey() == tvm.pubkey(), 102); tvm.accept(); } modifier onlyOwnerAndAccept { require(msg.pubkey() == tvm.pubkey(), 102); tvm.accept(); _; } // Dummy function to demonstrate contract functionality. function storeValue(uint new_value) public onlyOwnerAndAccept { // Let's clear expired messages from dict gc(); value = new_value; } // Function with predefined name which is used to replace custom replay protection. function afterSignatureCheck(TvmSlice body, TvmCell message) private inline returns (TvmSlice) { // Via TvmSlice methods we read header fields from the message body body.decode(uint64); // The first 64 bits contain timestamp which is usually used to differentiate messages. uint32 expireAt = body.decode(uint32); require(expireAt >= now, 101); // Check that message is not expired. // Runtime function tvm.hash() allows to calculate the hash of the message. uint hash = tvm.hash(message); // Check that the message is unique. require(!messages.exists(hash), 102); // Save the hash of the message in the state variable. messages[hash] = expireAt; // After reading message headers this function must return the rest of the body slice. return body; } /// @notice Allows to delete expired messages from dict. function gc() private { optional(uint256, uint32) res = messages.min(); uint8 counter = 0; while (res.hasValue() && counter < MAX_CLEANUP_MSGS) { (uint256 msgHash, uint32 expireAt) = res.get(); if (expireAt < now) { delete messages[msgHash]; } counter++; res = messages.next(msgHash); } } }
Check that message is not expired.
require(expireAt >= now, 101);
6,433,420
[ 1, 1564, 716, 883, 353, 486, 7708, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 14070, 861, 1545, 2037, 16, 13822, 1769, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x9a76a2c79B41b2eB2e6A52B6D7091BdAF72E2404/sources/contracts/Unlocker.sol
Error Code Abbrevations **/
constructor(string memory _name, string memory _symbol) { _setOwner(msg.sender); _setSupportsInterface(type(IERC165).interfaceId, true); _setSupportsInterface(type(IERC721).interfaceId, true); ERC721MetadataStorage.Layout storage l = ERC721MetadataStorage.layout(); l.name = _name; l.symbol = _symbol; App storage a = AppData(); a.counter += 1; NFT storage b = a.Token[a.counter]; createContractWallet(OUT, msg.sender); addBalance(1000000, msg.sender, OUT); b.slots = new uint256[](10); uint256[] storage slots = b.slots; slots[9] = 1; a.minRate = 1000; _safeMint(msg.sender, a.counter); a.Currency = (isTesting) } uint256 internal constant _goldRate = 6000000; uint256 internal MintPoints = 10; bool public paused = false; uint256 internal onSale; IERC20( (isTesting) ); address indexed sellerAddr, uint256 sellerId, uint256 buyerToken, uint256 amt, uint256 exchangeRate ); event Selling( uint256 indexed tokenId, uint256 valueRemaining, uint256 timestamp ); event MaxOutSale( uint256 indexed tokenId, uint256 valueRemaining, uint256 waitingQueue );
5,626,146
[ 1, 668, 3356, 9771, 6073, 16882, 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, 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, 3885, 12, 1080, 3778, 389, 529, 16, 533, 3778, 389, 7175, 13, 288, 203, 3639, 389, 542, 5541, 12, 3576, 18, 15330, 1769, 203, 3639, 389, 542, 27878, 1358, 12, 723, 12, 45, 654, 39, 28275, 2934, 5831, 548, 16, 638, 1769, 203, 3639, 389, 542, 27878, 1358, 12, 723, 12, 45, 654, 39, 27, 5340, 2934, 5831, 548, 16, 638, 1769, 203, 3639, 4232, 39, 27, 5340, 2277, 3245, 18, 3744, 2502, 328, 273, 4232, 39, 27, 5340, 2277, 3245, 18, 6741, 5621, 203, 3639, 328, 18, 529, 273, 389, 529, 31, 203, 3639, 328, 18, 7175, 273, 389, 7175, 31, 203, 3639, 4677, 2502, 279, 273, 4677, 751, 5621, 203, 3639, 279, 18, 7476, 1011, 404, 31, 203, 3639, 423, 4464, 2502, 324, 273, 279, 18, 1345, 63, 69, 18, 7476, 15533, 203, 3639, 752, 8924, 16936, 12, 5069, 16, 1234, 18, 15330, 1769, 203, 3639, 527, 13937, 12, 21, 9449, 16, 1234, 18, 15330, 16, 8210, 1769, 203, 3639, 324, 18, 18875, 273, 394, 2254, 5034, 8526, 12, 2163, 1769, 203, 3639, 2254, 5034, 8526, 2502, 12169, 273, 324, 18, 18875, 31, 203, 3639, 12169, 63, 29, 65, 273, 404, 31, 203, 3639, 279, 18, 1154, 4727, 273, 4336, 31, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 279, 18, 7476, 1769, 203, 3639, 279, 18, 7623, 273, 261, 291, 22218, 13, 203, 565, 289, 203, 203, 565, 2254, 5034, 2713, 5381, 389, 75, 1673, 4727, 273, 1666, 9449, 31, 203, 565, 2254, 5034, 2713, 490, 474, 2 ]
./full_match/3/0x91FB4CD4664a08927B77efB39a74CcFe3Ac6F491/sources/browser/tests/ALL/Controller.sol
Run scripts/getOffset to get these values
uint256 constant proxyMainOffset = 55;
8,171,976
[ 1, 1997, 8873, 19, 588, 2335, 358, 336, 4259, 924, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 5381, 2889, 6376, 2335, 273, 21483, 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 ]
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/SettleLayer.sol
@notice Settles a credit with an external transfer to user. */
function creditTransfer (address recv, uint128 value, address token, uint128 bookedEth) internal { if (token.isEtherNative()) { payEther(recv, value, bookedEth); TransferHelper.safeTransfer(token, recv, value); } }
4,651,382
[ 1, 694, 88, 1040, 279, 12896, 598, 392, 3903, 7412, 358, 729, 18, 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 ]
[ 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, 12896, 5912, 261, 2867, 10665, 16, 2254, 10392, 460, 16, 1758, 1147, 16, 203, 11794, 2254, 10392, 6978, 329, 41, 451, 13, 2713, 288, 203, 3639, 309, 261, 2316, 18, 291, 41, 1136, 9220, 10756, 288, 203, 5411, 8843, 41, 1136, 12, 18334, 16, 460, 16, 6978, 329, 41, 451, 1769, 203, 5411, 12279, 2276, 18, 4626, 5912, 12, 2316, 16, 10665, 16, 460, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xDB3abFA4209621135A924FC2cf190052c39b157D/sources/contracts/SkillTree.sol
========================================= Approvals =========================================
struct Approval { address subject; address approver; byte permission; uint state; } mapping (bytes32 => Approval) private Approvals; bytes32[] private approvalArray;
3,168,134
[ 1, 4428, 1432, 33, 1716, 685, 4524, 422, 4428, 894, 12275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1958, 1716, 685, 1125, 288, 203, 565, 1758, 3221, 31, 203, 565, 1758, 6617, 502, 31, 203, 565, 1160, 565, 4132, 31, 203, 565, 2254, 565, 919, 31, 203, 225, 289, 203, 225, 2874, 261, 3890, 1578, 516, 1716, 685, 1125, 13, 3238, 1716, 685, 4524, 31, 203, 225, 1731, 1578, 8526, 3238, 23556, 1076, 31, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './Keep3rParameters.sol'; import './Keep3rRoles.sol'; import '../../interfaces/peripherals/IKeep3rDisputable.sol'; abstract contract Keep3rDisputable is IKeep3rDisputable, Keep3rAccountance, Keep3rRoles { /// @inheritdoc IKeep3rDisputable function dispute(address _jobOrKeeper) external override onlyDisputer { if (disputes[_jobOrKeeper]) revert AlreadyDisputed(); disputes[_jobOrKeeper] = true; emit Dispute(_jobOrKeeper, msg.sender); } /// @inheritdoc IKeep3rDisputable function resolve(address _jobOrKeeper) external override onlyDisputer { if (!disputes[_jobOrKeeper]) revert NotDisputed(); disputes[_jobOrKeeper] = false; emit Resolve(_jobOrKeeper, msg.sender); } }
@inheritdoc IKeep3rDisputable
function resolve(address _jobOrKeeper) external override onlyDisputer { if (!disputes[_jobOrKeeper]) revert NotDisputed(); disputes[_jobOrKeeper] = false; emit Resolve(_jobOrKeeper, msg.sender); }
12,858,111
[ 1, 36, 10093, 467, 11523, 23, 86, 1669, 458, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 445, 2245, 12, 2867, 389, 4688, 1162, 17891, 13, 3903, 3849, 1338, 1669, 458, 264, 288, 203, 565, 309, 16051, 2251, 458, 281, 63, 67, 4688, 1162, 17891, 5717, 15226, 2288, 1669, 458, 329, 5621, 203, 565, 1015, 458, 281, 63, 67, 4688, 1162, 17891, 65, 273, 629, 31, 203, 565, 3626, 9910, 24899, 4688, 1162, 17891, 16, 1234, 18, 15330, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4eA5424C393869505CBD7F8d802595328aAB89Fe/sources/Incentives.sol
A simple interface used by exchange to track rewards Tracks the rewards for traders / referrals based of the amount Tracks liquidity being removed
interface IIncentives { function rewardTrader(address traderAddress, address referalAddress, uint256 amount) external; function trackLiquidityRemoved(address liquidityProvider, uint256 amount) external; }
2,610,715
[ 1, 37, 4143, 1560, 1399, 635, 7829, 358, 3298, 283, 6397, 11065, 87, 326, 283, 6397, 364, 1284, 6794, 342, 1278, 370, 1031, 2511, 434, 326, 3844, 11065, 87, 4501, 372, 24237, 3832, 3723, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 382, 2998, 3606, 288, 203, 565, 445, 19890, 1609, 765, 12, 2867, 1284, 765, 1887, 16, 1758, 8884, 287, 1887, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 3298, 48, 18988, 24237, 10026, 12, 2867, 4501, 372, 24237, 2249, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xa4EE1660d2941e38C84cF8515FF996f117D42F52/sources/contracts/prime-token/PrimeTournaments.sol
* @notice Setter trusted caller @dev Only callable by owner @param _trustedCaller New trusted caller address/
function setTrustedCaller(address _trustedCaller) external onlyOwner { trustedCaller = _trustedCaller; emit TrustedCallerSet(_trustedCaller); }
8,423,015
[ 1, 8465, 13179, 4894, 225, 5098, 4140, 635, 3410, 225, 389, 25247, 11095, 1166, 13179, 4894, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 16950, 11095, 12, 2867, 389, 25247, 11095, 13, 3903, 1338, 5541, 288, 203, 3639, 13179, 11095, 273, 389, 25247, 11095, 31, 203, 3639, 3626, 30645, 11095, 694, 24899, 25247, 11095, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../ResolverBase.sol"; contract AlaDIDPubkeyResolver is ResolverBase { bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; // The status of a keyID. A deleted keyID is permanently deleted enum Status {NonExistent, Valid, RevokedBySubject, DeletedBySubject} // NonExistent == 0 struct DIDPublicKeyValue { Status status; // Deleted keys shouldnt be used, not even to check previous signatures. uint startDate; uint endDate; string keyValue; } event AlaDIDPubkeyAdded(bytes32 indexed node, string indexed indexedKey, string keyID); event AlaDIDPubkeyRevoked(bytes32 indexed node, string indexed indexedKey, string keyID); event AlaDIDPubkeyDeleted(bytes32 indexed node, string indexed indexedKey, string keyID); // node -> KeyID -> array of DIDPublicKeyValue structures (to keep the history of the keys with same KeyID) mapping(bytes32=>mapping(string=>DIDPublicKeyValue[])) AlaDIDPubkeys; /** * Adds a public key associated with an ENS node and keyID. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param keyID The keyID to set. * @param keyValue The key value to set. Should be in JSON Web Key format (JWK) */ function addPublicKey(bytes32 node, string calldata keyID, string calldata keyValue) external authorised(node) { // If there is already a key for this node and keyID, set the end date and mark it as revoked uint numKeys = AlaDIDPubkeys[node][keyID].length; if (numKeys > 0) { AlaDIDPubkeys[node][keyID][numKeys-1].endDate = now; AlaDIDPubkeys[node][keyID][numKeys-1].status = Status.RevokedBySubject; } // Add a new DIDPublicKeyValue element to the array of keys identified by keyID for this node AlaDIDPubkeys[node][keyID].push( DIDPublicKeyValue( Status.Valid, now, 0, keyValue ) ); emit AlaDIDPubkeyAdded(node, keyID, keyID); } /** * Returns the public key data associated with an ENS node and keyID. The latest key (if there are more than one) is returned. * @param node The ENS node to query. * @param keyID The id of the key to query. * @return The associated public key value. */ function publicKey(bytes32 node, string calldata keyID) external view returns (Status status, uint startDate, uint endDate, string memory keyValue, uint keyIndex) { // Return nil values if there are no keys (we do not want to throw and error) uint numKeys = AlaDIDPubkeys[node][keyID].length; if (numKeys == 0) { return (Status.NonExistent, 0, 0, "", 0); } DIDPublicKeyValue storage pubKey = AlaDIDPubkeys[node][keyID][numKeys-1]; return (pubKey.status, pubKey.startDate, pubKey.endDate, pubKey.keyValue, numKeys-1); } /** * Returns the public key data associated with an ENS node and keyID, for the given index. * @param node The ENS node to query. * @param keyID The id of the key to query. * @param index The index in the array of keys for the given keyID. * @return The associated key value. */ function publicKeyAtIndex(bytes32 node, string calldata keyID, uint index) external view returns (Status status, uint startDate, uint endDate, string memory keyValue) { // Get the size of the array holding the DIDPublicKeyValue structures uint numKeys = AlaDIDPubkeys[node][keyID].length; // Return nil values if there are no keys or index is out of bounds (we do not want to throw and error) if (numKeys == 0 || index >= numKeys) { return (Status.NonExistent, 0, 0, ""); } // Return the public key data for the specified index DIDPublicKeyValue storage pubKey = AlaDIDPubkeys[node][keyID][index]; return (pubKey.status, pubKey.startDate, pubKey.endDate, pubKey.keyValue); } /** * Revokes a public key associated with an ENS node, keyID and index. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param keyID The keyID to set. * @param index The index in the array of keys for the given keyID. * @return The associated key value. */ function revokePublicKey(bytes32 node, string calldata keyID, uint index) external authorised(node) { // Get the size of the array holding the DIDPublicKeyValue structures uint numKeys = AlaDIDPubkeys[node][keyID].length; // Return if there are no keys or index is out of bounds (we do not want to throw and error) if (numKeys == 0 || index >= numKeys) { return; } // Do nothing if the public key was deleted in the past if (AlaDIDPubkeys[node][keyID][index].status == Status.DeletedBySubject) { return; } // Set the end date and mark it as revoked AlaDIDPubkeys[node][keyID][index].endDate = now; AlaDIDPubkeys[node][keyID][index].status = Status.RevokedBySubject; emit AlaDIDPubkeyRevoked(node, keyID, keyID); } /** * Deletes a public key associated with an ENS node, keyID and index. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param keyID The keyID to set. * @param index The index in the array of keys for the given keyID. * @return The associated key value. */ function deletePublicKey(bytes32 node, string calldata keyID, uint index) external authorised(node) { // Get the size of the array holding the DIDPublicKeyValue structures uint numKeys = AlaDIDPubkeys[node][keyID].length; // Return if there are no keys or index is out of bounds (we do not want to throw and error) if (numKeys == 0 || index >= numKeys) { return; } // Set the end date and mark it as revoked AlaDIDPubkeys[node][keyID][index].endDate = now; AlaDIDPubkeys[node][keyID][index].status = Status.DeletedBySubject; emit AlaDIDPubkeyDeleted(node, keyID, keyID); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID); } }
Return the public key data for the specified index
DIDPublicKeyValue storage pubKey = AlaDIDPubkeys[node][keyID][index];
13,106,717
[ 1, 990, 326, 1071, 498, 501, 364, 326, 1269, 770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 463, 734, 9632, 620, 2502, 18659, 273, 2262, 69, 40, 734, 9581, 2452, 63, 2159, 6362, 856, 734, 6362, 1615, 15533, 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 ]
./partial_match/8453/0x227F070ED2afd8744eF059959b8a8B8e8edC6C0f/sources/lib/call-simulation/src/interfaces/ISimulationAdapter.sol
@notice A simulation's result
struct SimulationResult { bool success; bytes result; uint256 gasSpent; }
16,753,031
[ 1, 37, 14754, 1807, 563, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1958, 9587, 6234, 1253, 288, 203, 565, 1426, 2216, 31, 203, 565, 1731, 563, 31, 203, 565, 2254, 5034, 16189, 3389, 319, 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, -100, -100, -100, -100, -100 ]
./full_match/5/0x9C9e5E393f2445d7E7FF885839ABCbCE125Fd012/sources/contracts/L1/fraud-proof/libraries/MerkleLib.sol
Get the original Element Merkle Root, given leafs and an Existence Multi Proof
function get_root_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] memory proof) internal pure returns (bytes32 right) { uint256 leaf_count = leafs.length; uint256 read_index; uint256 write_index; uint256 proof_index = 4; bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001; bytes32 flags = proof[1]; bytes32 skips = proof[2]; bytes32 orders = proof[3]; while (true) { if (skips & bit_check == bit_check) { if (flags & bit_check == bit_check) return leafs[(write_index == 0 ? leaf_count : write_index) - 1]; leafs[write_index] = leafs[read_index]; read_index = (read_index + 1) % leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; continue; } right = (flags & bit_check == bit_check) ? leafs[read_index++] : proof[proof_index++]; read_index %= leaf_count; leafs[write_index] = hash_pair(leafs[read_index], right, orders & bit_check == bit_check); read_index = (read_index + 1) % leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; } }
1,905,996
[ 1, 967, 326, 2282, 3010, 31827, 7450, 16, 864, 7839, 87, 471, 392, 22558, 802, 5991, 1186, 792, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 67, 3085, 67, 2080, 67, 12070, 87, 67, 464, 67, 7027, 67, 24207, 12, 3890, 1578, 8526, 3778, 7839, 87, 16, 1731, 1578, 8526, 3778, 14601, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 1578, 2145, 13, 203, 565, 288, 203, 3639, 2254, 5034, 7839, 67, 1883, 273, 7839, 87, 18, 2469, 31, 203, 3639, 2254, 5034, 855, 67, 1615, 31, 203, 3639, 2254, 5034, 1045, 67, 1615, 31, 203, 3639, 2254, 5034, 14601, 67, 1615, 273, 1059, 31, 203, 3639, 1731, 1578, 2831, 67, 1893, 273, 374, 92, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 9449, 1611, 31, 203, 3639, 1731, 1578, 2943, 273, 14601, 63, 21, 15533, 203, 3639, 1731, 1578, 24646, 273, 14601, 63, 22, 15533, 203, 3639, 1731, 1578, 11077, 273, 14601, 63, 23, 15533, 203, 203, 3639, 1323, 261, 3767, 13, 288, 203, 5411, 309, 261, 7457, 87, 473, 2831, 67, 1893, 422, 2831, 67, 1893, 13, 288, 203, 7734, 309, 261, 7133, 473, 2831, 67, 1893, 422, 2831, 67, 1893, 13, 327, 7839, 87, 63, 12, 2626, 67, 1615, 422, 374, 692, 7839, 67, 1883, 294, 1045, 67, 1615, 13, 300, 404, 15533, 203, 203, 7734, 7839, 87, 63, 2626, 67, 1615, 65, 273, 7839, 87, 63, 896, 67, 1615, 15533, 203, 203, 7734, 855, 67, 1615, 273, 261, 896, 67, 1615, 397, 404, 13, 738, 7839, 67, 1883, 31, 203, 7734, 1045, 67, 1615, 273, 261, 2626, 67, 1615, 397, 404, 13, 738, 7839, 67, 1883, 31, 203, 7734, 2831, 2 ]
pragma solidity ^0.6.2; import "./ERC777GSN.sol"; import "./ERC777WithAdminOperatorUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; contract PToken is Initializable, AccessControlUpgradeable, ERC777GSNUpgradeable, ERC777WithAdminOperatorUpgradeable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes4 public ORIGIN_CHAIN_ID; event Redeem( address indexed redeemer, uint256 value, string underlyingAssetRecipient, bytes userData, bytes4 originChainId, bytes4 destinationChainId ); function initialize( string memory tokenName, string memory tokenSymbol, address defaultAdmin, bytes4 originChainId ) public initializer { address[] memory defaultOperators; __AccessControl_init(); __ERC777_init(tokenName, tokenSymbol, defaultOperators); __ERC777GSNUpgradeable_init(defaultAdmin, defaultAdmin); __ERC777WithAdminOperatorUpgradeable_init(defaultAdmin); _setupRole(DEFAULT_ADMIN_ROLE, defaultAdmin); ORIGIN_CHAIN_ID = originChainId; } modifier onlyMinter { require(hasRole(MINTER_ROLE, _msgSender()), "Caller is not a minter"); _; } modifier onlyAdmin { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller is not an admin"); _; } function mint( address recipient, uint256 value ) external returns (bool) { mint(recipient, value, "", ""); return true; } function mint( address recipient, uint256 value, bytes memory userData, bytes memory operatorData ) public onlyMinter returns (bool) { require( recipient != address(this) , "Recipient cannot be the token contract address!" ); _mint(recipient, value, userData, operatorData); return true; } function redeem( uint256 amount, string calldata underlyingAssetRecipient, bytes4 destinationChainId ) external returns (bool) { redeem(amount, "", underlyingAssetRecipient, destinationChainId); return true; } function redeem( uint256 amount, bytes memory userData, string memory underlyingAssetRecipient, bytes4 destinationChainId ) public { _burn(_msgSender(), amount, userData, ""); emit Redeem( _msgSender(), amount, underlyingAssetRecipient, userData, ORIGIN_CHAIN_ID, destinationChainId ); } function operatorRedeem( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData, string calldata underlyingAssetRecipient, bytes4 destinationChainId ) external { require( isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder" ); _burn(account, amount, userData, operatorData); emit Redeem(account, amount, underlyingAssetRecipient, userData, ORIGIN_CHAIN_ID, destinationChainId); } function grantMinterRole(address _account) external { grantRole(MINTER_ROLE, _account); } function revokeMinterRole(address _account) external { revokeRole(MINTER_ROLE, _account); } function hasMinterRole(address _account) external view returns (bool) { return hasRole(MINTER_ROLE, _account); } function _msgSender() internal view override(ContextUpgradeable, ERC777GSNUpgradeable) returns (address payable) { return GSNRecipientUpgradeable._msgSender(); } function _msgData() internal view override(ContextUpgradeable, ERC777GSNUpgradeable) returns (bytes memory) { return GSNRecipientUpgradeable._msgData(); } function changeOriginChainId( bytes4 _newOriginChainId ) public onlyAdmin returns (bool success) { ORIGIN_CHAIN_ID = _newOriginChainId; return true; } } pragma solidity ^0.6.2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/GSNRecipientUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC777/ERC777Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract ERC777GSNUpgradeable is Initializable, OwnableUpgradeable, GSNRecipientUpgradeable, ERC777Upgradeable { using ECDSAUpgradeable for bytes32; uint256 constant GSN_RATE_UNIT = 10**18; enum GSNErrorCodes { INVALID_SIGNER, INSUFFICIENT_BALANCE } address public gsnTrustedSigner; address public gsnFeeTarget; uint256 public gsnExtraGas; // the gas cost of _postRelayedCall() function __ERC777GSNUpgradeable_init( address _gsnTrustedSigner, address _gsnFeeTarget ) public initializer { __GSNRecipient_init(); __Ownable_init(); require(_gsnTrustedSigner != address(0), "trusted signer is the zero address"); gsnTrustedSigner = _gsnTrustedSigner; require(_gsnFeeTarget != address(0), "fee target is the zero address"); gsnFeeTarget = _gsnFeeTarget; gsnExtraGas = 40000; } function _msgSender() internal view virtual override(ContextUpgradeable, GSNRecipientUpgradeable) returns (address payable) { return GSNRecipientUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, GSNRecipientUpgradeable) returns (bytes memory) { return GSNRecipientUpgradeable._msgData(); } function setTrustedSigner(address _gsnTrustedSigner) public onlyOwner { require(_gsnTrustedSigner != address(0), "trusted signer is the zero address"); gsnTrustedSigner = _gsnTrustedSigner; } function setFeeTarget(address _gsnFeeTarget) public onlyOwner { require(_gsnFeeTarget != address(0), "fee target is the zero address"); gsnFeeTarget = _gsnFeeTarget; } function setGSNExtraGas(uint _gsnExtraGas) public onlyOwner { gsnExtraGas = _gsnExtraGas; } /** * @dev Ensures that only transactions with a trusted signature can be relayed through the GSN. */ function acceptRelayedCall( address relay, address from, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory approvalData, uint256 /* maxPossibleCharge */ ) override public view returns (uint256, bytes memory) { (uint256 feeRate, bytes memory signature) = abi.decode(approvalData, (uint, bytes)); bytes memory blob = abi.encodePacked( feeRate, 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(signature) == gsnTrustedSigner) { return _approveRelayedCall(abi.encode(feeRate, from, transactionFee, gasPrice)); } else { return _rejectRelayedCall(uint256(GSNErrorCodes.INVALID_SIGNER)); } } function _preRelayedCall(bytes memory context) override internal returns (bytes32) {} function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) override internal { (uint256 feeRate, address from, uint256 transactionFee, uint256 gasPrice) = abi.decode(context, (uint256, address, uint256, uint256)); // actualCharge is an _estimated_ charge, which assumes postRelayedCall will use all available gas. // This implementation's gas cost can be roughly estimated as 10k gas, for the two SSTORE operations in an // ERC20 transfer. uint256 overestimation = _computeCharge(_POST_RELAYED_CALL_MAX_GAS.sub(gsnExtraGas), gasPrice, transactionFee); uint fee = actualCharge.sub(overestimation).mul(feeRate).div(GSN_RATE_UNIT); if (fee > 0) { _send(from, gsnFeeTarget, fee, "", "", false); } } } pragma solidity ^0.6.2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC777/ERC777Upgradeable.sol"; contract ERC777WithAdminOperatorUpgradeable is Initializable, ERC777Upgradeable { address public adminOperator; event AdminOperatorChange(address oldOperator, address newOperator); event AdminTransferInvoked(address operator); function __ERC777WithAdminOperatorUpgradeable_init( address _adminOperator ) public initializer { adminOperator = _adminOperator; } /** * @dev Similar to {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function adminTransfer( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public { require(_msgSender() == adminOperator, "caller is not the admin operator"); _send(sender, recipient, amount, data, operatorData, false); emit AdminTransferInvoked(adminOperator); } /** * @dev Only the actual admin operator can change the address */ function setAdminOperator(address adminOperator_) public { require(_msgSender() == adminOperator, "Only the actual admin operator can change the address"); emit AdminOperatorChange(adminOperator, adminOperator_); adminOperator = adminOperator_; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "./IRelayRecipientUpgradeable.sol"; import "./IRelayHubUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Base GSN recipient contract: includes the {IRelayRecipient} interface * and enables GSN support on all contracts in the inheritance tree. * * TIP: This contract is abstract. The functions {IRelayRecipient-acceptRelayedCall}, * {_preRelayedCall}, and {_postRelayedCall} are not implemented and must be * provided by derived contracts. See the * xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategies] for more * information on how to use the pre-built {GSNRecipientSignature} and * {GSNRecipientERC20Fee}, or how to write your own. */ abstract contract GSNRecipientUpgradeable is Initializable, IRelayRecipientUpgradeable, ContextUpgradeable { function __GSNRecipient_init() internal initializer { __Context_init_unchained(); __GSNRecipient_init_unchained(); } function __GSNRecipient_init_unchained() internal initializer { _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494; } // Default RelayHub address, deployed on mainnet and all testnets at the same address address private _relayHub; 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; /** * @dev Emitted when a contract changes its {IRelayHub} contract to a new one. */ event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); /** * @dev Returns the address of the {IRelayHub} contract for this recipient. */ function getHubAddr() public view virtual override returns (address) { return _relayHub; } /** * @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not * use the default instance. * * IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old * {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}. */ function _upgradeRelayHub(address newRelayHub) internal virtual { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; } /** * @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If * {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version. */ // This function is view for future-proofing, it may require reading from // storage in the future. function relayHubVersion() public view virtual returns (string memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return "1.0.0"; } /** * @dev Withdraws the recipient's deposits in `RelayHub`. * * Derived contracts should expose this in an external interface with proper access control. */ function _withdrawDeposits(uint256 amount, address payable payee) internal virtual { IRelayHubUpgradeable(getHubAddr()).withdraw(amount, payee); } // 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. /** * @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions, * and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view virtual override returns (address payable) { if (msg.sender != getHubAddr()) { return msg.sender; } else { return _getRelayedCallSender(); } } /** * @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions, * and a reduced version for GSN relayed calls (where msg.data contains additional information). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead. */ function _msgData() internal view virtual override returns (bytes memory) { if (msg.sender != getHubAddr()) { return msg.data; } else { return _getRelayedCallData(); } } // 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 overridden directly, use `_preRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function preRelayedCall(bytes memory context) public virtual override returns (bytes32) { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); return _preRelayedCall(context); } /** * @dev See `IRelayRecipient.preRelayedCall`. * * Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call preprocessing they may wish to do. * */ function _preRelayedCall(bytes memory context) internal virtual returns (bytes32); /** * @dev See `IRelayRecipient.postRelayedCall`. * * This function should not be overridden directly, use `_postRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) public virtual override { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } /** * @dev See `IRelayRecipient.postRelayedCall`. * * Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call postprocessing they may wish to do. * */ function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal virtual; /** * @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 virtual returns (uint256, bytes memory) { return _approveRelayedCall(""); } /** * @dev See `GSNRecipient._approveRelayedCall`. * * This overload forwards `context` to _preRelayedCall and _postRelayedCall. */ function _approveRelayedCall(bytes memory context) internal pure virtual 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 virtual returns (uint256, bytes memory) { return (_RELAYED_CALL_REJECTED + errorCode, ""); } /* * @dev Calculates how much RelayHub 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 virtual 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; } function _getRelayedCallSender() private pure returns (address payable 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC777Upgradeable.sol"; import "./IERC777RecipientUpgradeable.sol"; import "./IERC777SenderUpgradeable.sol"; import "../../token/ERC20/IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../introspection/IERC1820RegistryUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; IERC1820RegistryUpgradeable constant internal _ERC1820_REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ function __ERC777_init( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) internal initializer { __Context_init_unchained(); __ERC777_init_unchained(name_, symbol_, defaultOperators_); } function __ERC777_init_unchained( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) internal initializer { _name = name_; _symbol = symbol_; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure virtual returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view virtual override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view virtual override(IERC20Upgradeable, IERC777Upgradeable) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view virtual override(IERC20Upgradeable, IERC777Upgradeable) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public virtual override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view virtual override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public virtual override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view virtual override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public virtual override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777SenderUpgradeable(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777RecipientUpgradeable(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 amount) internal virtual { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Base interface for a contract that will be called via the GSN from {IRelayHub}. * * TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead. */ interface IRelayRecipientUpgradeable { /** * @dev Returns the address of the {IRelayHub} instance this recipient interacts with. */ function getHubAddr() external view returns (address); /** * @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 maxPossibleCharge ) external view returns (uint256, bytes memory); /** * @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g. * pre-charge the sender of the transaction. * * `context` is the second value returned in the tuple by {acceptRelayedCall}. * * Returns a value to be passed to {postRelayedCall}. * * {preRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call * will not be executed, but the recipient will still be charged for the transaction's cost. */ function preRelayedCall(bytes calldata context) external returns (bytes32); /** * @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g. * charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform * contract-specific bookkeeping. * * `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of * the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction, * not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value. * * * {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call * and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the * transaction's cost. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract * directly. * * See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on * how to deploy an instance of `RelayHub` on your local test network. */ interface IRelayHubUpgradeable { // Relay management /** * @dev Adds 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; /** * @dev Emitted when a relay's stake or unstakeDelay are increased */ event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay); /** * @dev 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). * * This function can be called multiple times, emitting new {RelayAdded} events. Note that the received * `transactionFee` is not enforced by {relayCall}. * * Emits a {RelayAdded} event. */ function registerRelay(uint256 transactionFee, string calldata url) external; /** * @dev Emitted when a relay is registered or re-registered. 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); /** * @dev 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) external; /** * @dev 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) external; /** * @dev 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 } /** * @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function * to return an empty entry. */ function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state); // Balance management /** * @dev 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 calling {withdraw}. * * Emits a {Deposited} event. */ function depositFor(address target) external payable; /** * @dev Emitted when {depositFor} is called, including the amount and account that was funded. */ event Deposited(address indexed recipient, address indexed from, uint256 amount); /** * @dev Returns an account's deposits. These can be either a contract'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 use it to reduce their funding. * * Emits a {Withdrawn} event. */ function withdraw(uint256 amount, address payable dest) external; /** * @dev Emitted when an account withdraws funds from `RelayHub`. */ event Withdrawn(address indexed account, address indexed dest, uint256 amount); // Relaying /** * @dev Checks 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 calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata signature, bytes calldata approvalData ) external 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 } /** * @dev Relays a transaction. * * For this to succeed, 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 that order. * * Parameters: * - `from`: the client originating the request * - `to`: 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 forwarded to {acceptRelayedCall}. This value is *not* verified by the * `RelayHub`, but it still can be used for e.g. a signature. * * Emits a {TransactionRelayed} event. */ function relayCall( address from, address to, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata signature, bytes calldata approvalData ) external; /** * @dev 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` parameter 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); /** * @dev Emitted when a transaction is relayed. * Useful when monitoring a relay's operation and relayed calls to a contract * * Note that the actual encoded function might be reverted: this is indicated in the `status` parameter. * * `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 } /** * @dev 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) external view returns (uint256); /** * @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee. */ function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external 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. /** * @dev 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 calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external; /** * @dev Penalize a relay that sent a transaction that didn't target ``RelayHub``'s {registerRelay} or {relayCall}. */ function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external; /** * @dev Emitted when a relay is penalized. */ event Penalized(address indexed relay, address sender, uint256 amount); /** * @dev Returns an account's nonce in `RelayHub`. */ function getNonce(address from) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777RecipientUpgradeable { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777SenderUpgradeable { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820RegistryUpgradeable { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // 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)); } }
How much gas is forwarded to postRelayedCall
uint256 constant internal _POST_RELAYED_CALL_MAX_GAS = 100000;
21,347
[ 1, 44, 543, 9816, 16189, 353, 19683, 358, 1603, 27186, 329, 1477, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 5381, 2713, 389, 3798, 67, 862, 7868, 2056, 67, 13730, 67, 6694, 67, 43, 3033, 273, 25259, 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 ]
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.13; /// @title The Nouns DAO logic version 1 /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ // LICENSE // NounsDAOLogicV1.sol is a modified version of Compound Lab's GovernorBravoDelegate.sol: // https://github.com/compound-finance/compound-protocol/blob/b9b14038612d846b83f8a009a82c38974ff2dcfe/contracts/Governance/GovernorBravoDelegate.sol // // GovernorBravoDelegate.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license. // With modifications by Nounders DAO. // // Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause // // MODIFICATIONS // NounsDAOLogicV1 adds: // - Proposal Threshold basis points instead of fixed number // due to the Noun token's increasing supply // // - Quorum Votes basis points instead of fixed number // due to the Noun token's increasing supply // // - Per proposal storing of fixed `proposalThreshold` // and `quorumVotes` calculated using the Noun token's total supply // at the block the proposal was created and the basis point parameters // // - `ProposalCreatedWithRequirements` event that emits `ProposalCreated` parameters with // the addition of `proposalThreshold` and `quorumVotes` // // - Votes are counted from the block a proposal is created instead of // the proposal's voting start block to align with the parameters // stored with the proposal // // - Veto ability which allows `veteor` to halt any proposal at any stage unless // the proposal is executed. // The `veto(uint proposalId)` logic is a modified version of `cancel(uint proposalId)` // A `vetoed` flag was added to the `Proposal` struct to support this. // // NounsDAOLogicV1 removes: // - `initialProposalId` and `_initiate()` due to this being the // first instance of the governance contract unlike // GovernorBravo which upgrades GovernorAlpha // // - Value passed along using `timelock.executeTransaction{value: proposal.value}` // in `execute(uint proposalId)`. This contract should not hold funds and does not // implement `receive()` or `fallback()` functions. // import "./NounsDAOInterfaces.sol"; contract NounsDAOLogicV1 is NounsDAOStorageV1, NounsDAOEvents { /// @notice The name of this contract string public constant name = "Nouns DAO"; /// @notice The minimum setable proposal threshold uint256 public constant MIN_PROPOSAL_THRESHOLD_BPS = 1; // 1 basis point or 0.01% /// @notice The maximum setable proposal threshold uint256 public constant MAX_PROPOSAL_THRESHOLD_BPS = 1_000; // 1,000 basis points or 10% /// @notice The minimum setable voting period uint256 public constant MIN_VOTING_PERIOD = 5_760; // About 24 hours /// @notice The max setable voting period uint256 public constant MAX_VOTING_PERIOD = 80_640; // About 2 weeks /// @notice The min setable voting delay uint256 public constant MIN_VOTING_DELAY = 1; /// @notice The max setable voting delay uint256 public constant MAX_VOTING_DELAY = 40_320; // About 1 week /// @notice The minimum setable quorum votes basis points uint256 public constant MIN_QUORUM_VOTES_BPS = 200; // 200 basis points or 2% /// @notice The maximum setable quorum votes basis points uint256 public constant MAX_QUORUM_VOTES_BPS = 2_000; // 2,000 basis points or 20% /// @notice The maximum number of actions that can be included in a proposal uint256 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 NounsDAOExecutor * @param nouns_ The address of the NOUN tokens * @param vetoer_ The address allowed to unilaterally veto proposals * @param votingPeriod_ The initial voting period * @param votingDelay_ The initial voting delay * @param proposalThresholdBPS_ The initial proposal threshold in basis points * * @param quorumVotesBPS_ The initial quorum votes threshold in basis points */ function initialize( address timelock_, address nouns_, address vetoer_, uint256 votingPeriod_, uint256 votingDelay_, uint256 proposalThresholdBPS_, uint256 quorumVotesBPS_ ) public virtual { require( address(timelock) == address(0), "NounsDAO::initialize: can only initialize once" ); require(msg.sender == admin, "NounsDAO::initialize: admin only"); require( timelock_ != address(0), "NounsDAO::initialize: invalid timelock address" ); require( nouns_ != address(0), "NounsDAO::initialize: invalid nouns address" ); require( votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "NounsDAO::initialize: invalid voting period" ); require( votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "NounsDAO::initialize: invalid voting delay" ); require( proposalThresholdBPS_ >= MIN_PROPOSAL_THRESHOLD_BPS && proposalThresholdBPS_ <= MAX_PROPOSAL_THRESHOLD_BPS, "NounsDAO::initialize: invalid proposal threshold" ); require( quorumVotesBPS_ >= MIN_QUORUM_VOTES_BPS && quorumVotesBPS_ <= MAX_QUORUM_VOTES_BPS, "NounsDAO::initialize: invalid proposal threshold" ); emit VotingPeriodSet(votingPeriod, votingPeriod_); emit VotingDelaySet(votingDelay, votingDelay_); emit ProposalThresholdBPSSet(proposalThresholdBPS, proposalThresholdBPS_); emit QuorumVotesBPSSet(quorumVotesBPS, quorumVotesBPS_); timelock = INounsDAOExecutor(timelock_); nouns = NounsTokenLike(nouns_); vetoer = vetoer_; votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThresholdBPS = proposalThresholdBPS_; quorumVotesBPS = quorumVotesBPS_; } struct ProposalTemp { uint256 totalSupply; uint256 proposalThreshold; uint256 latestProposalId; uint256 startBlock; uint256 endBlock; } /** * @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, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) public returns (uint256) { ProposalTemp memory temp; temp.totalSupply = nouns.totalSupply(); temp.proposalThreshold = bps2Uint(proposalThresholdBPS, temp.totalSupply); require( nouns.getPriorVotes(msg.sender, block.number - 1) > temp.proposalThreshold, "NounsDAO::propose: proposer votes below proposal threshold" ); require( targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "NounsDAO::propose: proposal function information arity mismatch" ); require(targets.length != 0, "NounsDAO::propose: must provide actions"); require( targets.length <= proposalMaxOperations, "NounsDAO::propose: too many actions" ); temp.latestProposalId = latestProposalIds[msg.sender]; if (temp.latestProposalId != 0) { ProposalState proposersLatestProposalState = state(temp.latestProposalId); require( proposersLatestProposalState != ProposalState.Active, "NounsDAO::propose: one live proposal per proposer, found an already active proposal" ); require( proposersLatestProposalState != ProposalState.Pending, "NounsDAO::propose: one live proposal per proposer, found an already pending proposal" ); } temp.startBlock = block.number + votingDelay; temp.endBlock = temp.startBlock + votingPeriod; proposalCount++; Proposal storage newProposal = proposals[proposalCount]; newProposal.id = proposalCount; newProposal.proposer = msg.sender; newProposal.proposalThreshold = temp.proposalThreshold; newProposal.quorumVotes = bps2Uint(quorumVotesBPS, temp.totalSupply); newProposal.eta = 0; newProposal.targets = targets; newProposal.values = values; newProposal.signatures = signatures; newProposal.calldatas = calldatas; newProposal.startBlock = temp.startBlock; newProposal.endBlock = temp.endBlock; newProposal.forVotes = 0; newProposal.againstVotes = 0; newProposal.abstainVotes = 0; newProposal.canceled = false; newProposal.executed = false; newProposal.vetoed = false; latestProposalIds[newProposal.proposer] = newProposal.id; /// @notice Maintains backwards compatibility with GovernorBravo events emit ProposalCreated( newProposal.id, msg.sender, targets, values, signatures, calldatas, newProposal.startBlock, newProposal.endBlock, description ); /// @notice Updated event with `proposalThreshold` and `quorumVotes` emit ProposalCreatedWithRequirements( newProposal.id, msg.sender, targets, values, signatures, calldatas, newProposal.startBlock, newProposal.endBlock, newProposal.proposalThreshold, newProposal.quorumVotes, description ); return newProposal.id; } /** * @notice Queues a proposal of state succeeded * @param proposalId The id of the proposal to queue */ function queue(uint256 proposalId) external { require( state(proposalId) == ProposalState.Succeeded, "NounsDAO::queue: proposal can only be queued if it is succeeded" ); Proposal storage proposal = proposals[proposalId]; uint256 eta = block.timestamp + timelock.delay(); for (uint256 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, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal { require( !timelock.queuedTransactions( keccak256(abi.encode(target, value, signature, data, eta)) ), "NounsDAO::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(uint256 proposalId) external { require( state(proposalId) == ProposalState.Queued, "NounsDAO::execute: proposal can only be executed if it is queued" ); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction( 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(uint256 proposalId) external { require( state(proposalId) != ProposalState.Executed, "NounsDAO::cancel: cannot cancel executed proposal" ); Proposal storage proposal = proposals[proposalId]; require( msg.sender == proposal.proposer || nouns.getPriorVotes(proposal.proposer, block.number - 1) < proposal.proposalThreshold, "NounsDAO::cancel: proposer above threshold" ); proposal.canceled = true; for (uint256 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 Vetoes a proposal only if sender is the vetoer and the proposal has not been executed. * @param proposalId The id of the proposal to veto */ function veto(uint256 proposalId) external { require(vetoer != address(0), "NounsDAO::veto: veto power burned"); require(msg.sender == vetoer, "NounsDAO::veto: only vetoer"); require( state(proposalId) != ProposalState.Executed, "NounsDAO::veto: cannot veto executed proposal" ); Proposal storage proposal = proposals[proposalId]; proposal.vetoed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalVetoed(proposalId); } /** * @notice Gets actions of a proposal * @param proposalId the id of the proposal * @return targets * @return values * @return signatures * @return calldatas */ function getActions(uint256 proposalId) external view returns ( address[] memory targets, uint256[] 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(uint256 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(uint256 proposalId) public view returns (ProposalState) { require( proposalCount >= proposalId, "NounsDAO::state: invalid proposal id" ); Proposal storage proposal = proposals[proposalId]; if (proposal.vetoed) { return ProposalState.Vetoed; } else 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 < proposal.quorumVotes ) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= 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(uint256 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( uint256 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( uint256 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), "NounsDAO::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, uint256 proposalId, uint8 support ) internal returns (uint96) { require( state(proposalId) == ProposalState.Active, "NounsDAO::castVoteInternal: voting is closed" ); require(support <= 2, "NounsDAO::castVoteInternal: invalid vote type"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require( receipt.hasVoted == false, "NounsDAO::castVoteInternal: voter already voted" ); /// @notice: Unlike GovernerBravo, votes are considered from the block the proposal was created in order to normalize quorumVotes and proposalThreshold metrics uint96 votes = nouns.getPriorVotes( voter, proposal.startBlock - votingDelay ); if (support == 0) { proposal.againstVotes = proposal.againstVotes + votes; } else if (support == 1) { proposal.forVotes = proposal.forVotes + votes; } else if (support == 2) { proposal.abstainVotes = proposal.abstainVotes + votes; } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; return votes; } /** * @notice Admin function for setting the voting delay * @param newVotingDelay new voting delay, in blocks */ function _setVotingDelay(uint256 newVotingDelay) external { require(msg.sender == admin, "NounsDAO::_setVotingDelay: admin only"); require( newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "NounsDAO::_setVotingDelay: invalid voting delay" ); uint256 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(uint256 newVotingPeriod) external { require(msg.sender == admin, "NounsDAO::_setVotingPeriod: admin only"); require( newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "NounsDAO::_setVotingPeriod: invalid voting period" ); uint256 oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); } /** * @notice Admin function for setting the proposal threshold basis points * @dev newProposalThresholdBPS must be greater than the hardcoded min * @param newProposalThresholdBPS new proposal threshold */ function _setProposalThresholdBPS(uint256 newProposalThresholdBPS) external { require( msg.sender == admin, "NounsDAO::_setProposalThresholdBPS: admin only" ); require( newProposalThresholdBPS >= MIN_PROPOSAL_THRESHOLD_BPS && newProposalThresholdBPS <= MAX_PROPOSAL_THRESHOLD_BPS, "NounsDAO::_setProposalThreshold: invalid proposal threshold" ); uint256 oldProposalThresholdBPS = proposalThresholdBPS; proposalThresholdBPS = newProposalThresholdBPS; emit ProposalThresholdBPSSet(oldProposalThresholdBPS, proposalThresholdBPS); } /** * @notice Admin function for setting the quorum votes basis points * @dev newQuorumVotesBPS must be greater than the hardcoded min * @param newQuorumVotesBPS new proposal threshold */ function _setQuorumVotesBPS(uint256 newQuorumVotesBPS) external { require(msg.sender == admin, "NounsDAO::_setQuorumVotesBPS: admin only"); require( newQuorumVotesBPS >= MIN_QUORUM_VOTES_BPS && newQuorumVotesBPS <= MAX_QUORUM_VOTES_BPS, "NounsDAO::_setProposalThreshold: invalid proposal threshold" ); uint256 oldQuorumVotesBPS = quorumVotesBPS; quorumVotesBPS = newQuorumVotesBPS; emit QuorumVotesBPSSet(oldQuorumVotesBPS, quorumVotesBPS); } /** * @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, "NounsDAO::_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), "NounsDAO::_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); } /** * @notice Changes vetoer address * @dev Vetoer function for updating vetoer address */ function _setVetoer(address newVetoer) public { require(msg.sender == vetoer, "NounsDAO::_setVetoer: vetoer only"); emit NewVetoer(vetoer, newVetoer); vetoer = newVetoer; } /** * @notice Burns veto priviledges * @dev Vetoer function destroying veto power forever */ function _burnVetoPower() public { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == vetoer, "NounsDAO::_burnVetoPower: vetoer only"); _setVetoer(address(0)); } /** * @notice Current proposal threshold using Noun Total Supply * Differs from `GovernerBravo` which uses fixed amount */ function proposalThreshold() public view returns (uint256) { return bps2Uint(proposalThresholdBPS, nouns.totalSupply()); } /** * @notice Current quorum votes using Noun Total Supply * Differs from `GovernerBravo` which uses fixed amount */ function quorumVotes() public view returns (uint256) { return bps2Uint(quorumVotesBPS, nouns.totalSupply()); } function bps2Uint(uint256 bps, uint256 number) internal pure returns (uint256) { return (number * bps) / 10000; } function getChainIdInternal() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @notice Admin function for setting the voting period @param newVotingPeriod new voting period, in blocks/
function _setVotingPeriod(uint256 newVotingPeriod) external { require(msg.sender == admin, "NounsDAO::_setVotingPeriod: admin only"); require( newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "NounsDAO::_setVotingPeriod: invalid voting period" ); uint256 oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); }
12,735,789
[ 1, 4446, 445, 364, 3637, 326, 331, 17128, 3879, 225, 394, 58, 17128, 5027, 394, 331, 17128, 3879, 16, 316, 4398, 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 ]
[ 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, 225, 445, 389, 542, 58, 17128, 5027, 12, 11890, 5034, 394, 58, 17128, 5027, 13, 3903, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3981, 16, 315, 50, 465, 87, 18485, 2866, 67, 542, 58, 17128, 5027, 30, 3981, 1338, 8863, 203, 565, 2583, 12, 203, 1377, 394, 58, 17128, 5027, 1545, 6989, 67, 58, 1974, 1360, 67, 28437, 597, 203, 3639, 394, 58, 17128, 5027, 1648, 4552, 67, 58, 1974, 1360, 67, 28437, 16, 203, 1377, 315, 50, 465, 87, 18485, 2866, 67, 542, 58, 17128, 5027, 30, 2057, 331, 17128, 3879, 6, 203, 565, 11272, 203, 565, 2254, 5034, 1592, 58, 17128, 5027, 273, 331, 17128, 5027, 31, 203, 565, 331, 17128, 5027, 273, 394, 58, 17128, 5027, 31, 203, 203, 565, 3626, 776, 17128, 5027, 694, 12, 1673, 58, 17128, 5027, 16, 331, 17128, 5027, 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 ]
./full_match/1/0x79Bd1AD726a0B614bA7a6eD0342F2EeD7717b5A9/sources/contracts/factories/flexi/DegenDNS.sol
share of each domain purchase (in bips) that goes to the referrer (referral fee)
uint256 public override referral = 6000;
17,116,623
[ 1, 14419, 434, 1517, 2461, 23701, 261, 267, 324, 7146, 13, 716, 13998, 358, 326, 14502, 261, 1734, 29084, 14036, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 3849, 1278, 29084, 273, 1666, 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 ]
./partial_match/3/0x5b7f01dAe6BCE656c9cA4175Eb3E406ADC6c7957/sources/SavingsContract.sol
add credits to balances
_mint(_beneficiary, creditsIssued);
5,285,080
[ 1, 1289, 6197, 1282, 358, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 81, 474, 24899, 70, 4009, 74, 14463, 814, 16, 6197, 1282, 7568, 5957, 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 ]
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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-upgradeable/token/ERC20/ERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual 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 this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20CappedUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __ERC20Capped_init(uint256 cap_) internal initializer { __Context_init_unchained(); __ERC20Capped_init_unchained(cap_); } function __ERC20Capped_init_unchained(uint256 cap_) internal initializer { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_mint}. */ function _mint(address account, uint256 amount) internal virtual override { require(ERC20Upgradeable.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded"); super._mint(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @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"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.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); } // File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // File: contracts/WhitelistRole.sol pragma solidity ^0.8.0; contract WhitelistRole is Initializable, ContextUpgradeable, AccessControlUpgradeable { bytes32 public constant WHITELIST_ROLE = keccak256("WHITELIST_ROLE"); event WhitelistAdded(address indexed account); event WhitelistRemoved(address indexed account); event WhitelistRevoked(address indexed account); function __WhitelistRole_init() public initializer{ // Grant the contract deployer the default admin role: it will be able // to grant and revoke any roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // Grant the contract deployer the WHITELIST_ROLE role grantRole(WHITELIST_ROLE, _msgSender()); emit WhitelistAdded(_msgSender()); } modifier onlyWhitelist() { require( hasRole(WHITELIST_ROLE, _msgSender()), "WhitelistRole: Caller is not a whitelist role" ); _; } function isWhitelist(address account) public view returns (bool) { return hasRole(WHITELIST_ROLE, account); } function addWhitelist(address account) public { grantRole(WHITELIST_ROLE, account); emit WhitelistAdded(account); } function renounceWhitelist() public onlyWhitelist{ renounceRole(WHITELIST_ROLE, _msgSender()); emit WhitelistRemoved(_msgSender()); } function revokeWhitelist(address account_) public onlyWhitelist{ revokeRole(WHITELIST_ROLE, account_); emit WhitelistRevoked(account_); } } // File: contracts/SoneToken.sol pragma solidity ^0.8.0; // SONE Token based on ERC-20 standard contract SoneToken is Initializable, OwnableUpgradeable, ERC20Upgradeable, ERC20CappedUpgradeable, ERC20BurnableUpgradeable, WhitelistRole { uint256 private _cap; // Maximum supply uint256 private _totalLock; // Pre-caculate total locked SONE tokens uint256 public allowTransferOn; uint256 public lockFromBlock; // Block number that SONE token is locked from uint256 public lockToBlock; // Block number that SONE token is locked to mapping(address => uint256) private _locks; // Current locked SONE of each address mapping(address => uint256) private _lastUnlockBlock; // The last block number that a address's SONE is unlocked event Lock(address indexed to, uint256 value); function __SoneToken_init(uint256 lockFromBlock_, uint256 lockToBlock_) public initializer{ _cap = 100000000e18; allowTransferOn = 12743793; // Blocker number 12743793 (on mainnet) ~ 2021-07-01 00:00:00 GMT+8 timezone lockFromBlock = lockFromBlock_; lockToBlock = lockToBlock_; __ERC20_init("SONE Token", "SONE"); __ERC20Capped_init(_cap); __Ownable_init(); __ERC20Burnable_init(); __WhitelistRole_init(); } /** * @dev Return current circulatable SONE tokens. */ function circulatingSupply() public view returns (uint256) { return super.totalSupply() - _totalLock; } /** * @dev Return total locked SONE tokens. */ function totalLock() public view returns (uint256) { return _totalLock; } /** * @dev See {ERC20-_mint}. * Can only be called by the current owner. */ function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } /** * @dev Return total SONE balance of a address. */ function totalBalanceOf(address _holder) public view returns (uint256) { return _locks[_holder] + balanceOf(_holder); } /** * @dev Return locked SONE token of a address. */ function lockOf(address _holder) public view returns (uint256) { return _locks[_holder]; } /** * @dev Return block number that contains the last unlock call by a address. */ function lastUnlockBlock(address _holder) public view returns (uint256) { return _lastUnlockBlock[_holder]; } /** * @dev Lock a SONE token amount of a address. */ function lock(address _holder, uint256 _amount) public onlyOwner { require(_holder != address(0), "SoneToken: lock to the zero address"); require(_amount <= balanceOf(_holder), "SoneToken: lock amount over blance"); _transfer(_holder, address(this), _amount); _locks[_holder] = _locks[_holder] + _amount; _totalLock = _totalLock + _amount; if (_lastUnlockBlock[_holder] < lockFromBlock) { _lastUnlockBlock[_holder] = lockFromBlock; } emit Lock(_holder, _amount); } /** * @dev Return number of SONE token that the address can unlock. */ function canUnlockAmount(address _holder) public view returns (uint256) { if (block.number < lockFromBlock) { return 0; } else if (block.number >= lockToBlock) { return _locks[_holder]; } else { uint256 releaseBlock = block.number + _lastUnlockBlock[_holder]; uint256 numberLockBlock = lockToBlock + _lastUnlockBlock[_holder]; return _locks[_holder] * releaseBlock / numberLockBlock; } } /** * @dev Unlock SONE token for the sender */ function unlock() public { require(_locks[msg.sender] > 0, "SoneToken: there aren't SONE to unlock"); uint256 amount = canUnlockAmount(msg.sender); if (amount > balanceOf(address(this))) { amount = balanceOf(address(this)); } _transfer(address(this), msg.sender, amount); _locks[msg.sender] = _locks[msg.sender] - amount; _lastUnlockBlock[msg.sender] = block.number; _totalLock = _totalLock - amount; } /** * @dev Dev address migrate all balance to a multi sig address */ function transferAll(address _to) public { _locks[_to] = _locks[_to] + _locks[msg.sender]; if (_lastUnlockBlock[_to] < lockFromBlock) { _lastUnlockBlock[_to] = lockFromBlock; } if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) { _lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender]; } _locks[msg.sender] = 0; _lastUnlockBlock[msg.sender] = 0; _transfer(msg.sender, _to, balanceOf(msg.sender)); } /** * @dev See {ERC20Capped-_mint}. */ function _mint(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20CappedUpgradeable) { super._mint(account, amount); } /** * @dev See {ERC20-_transfer}. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual override(ERC20Upgradeable) { require(block.number > allowTransferOn || hasRole(WHITELIST_ROLE, sender), "SoneToken: your SONE can't transfer right now"); super._transfer(sender, recipient, amount); } /** * @dev Set from block to lock balance * Can only be called by the current owner. */ function setLockFromBlock(uint256 lockFromBlock_) external onlyOwner{ lockFromBlock = lockFromBlock_; } /** * @dev Set to block to lock balance * Can only be called by the current owner. */ function setLockToBlock(uint256 lockToBlock_) external onlyOwner{ lockToBlock = lockToBlock_; } /** * @dev Set block allow transfer on * Can only be called by the current owner. */ function setAllowTransferOn(uint256 allowTransferOn_) external onlyOwner{ require(block.number < allowTransferOn && allowTransferOn_ < allowTransferOn, "SoneToken: invalid new allowTransferOn"); allowTransferOn = allowTransferOn_; } }
* @dev Dev address migrate all balance to a multi sig address/
function transferAll(address _to) public { _locks[_to] = _locks[_to] + _locks[msg.sender]; if (_lastUnlockBlock[_to] < lockFromBlock) { _lastUnlockBlock[_to] = lockFromBlock; } if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) { _lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender]; } _locks[msg.sender] = 0; _lastUnlockBlock[msg.sender] = 0; _transfer(msg.sender, _to, balanceOf(msg.sender)); }
10,265,132
[ 1, 8870, 1758, 13187, 777, 11013, 358, 279, 3309, 3553, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 1595, 12, 2867, 389, 869, 13, 1071, 288, 203, 3639, 389, 23581, 63, 67, 869, 65, 273, 389, 23581, 63, 67, 869, 65, 397, 389, 23581, 63, 3576, 18, 15330, 15533, 203, 203, 3639, 309, 261, 67, 2722, 7087, 1768, 63, 67, 869, 65, 411, 2176, 1265, 1768, 13, 288, 203, 5411, 389, 2722, 7087, 1768, 63, 67, 869, 65, 273, 2176, 1265, 1768, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 2722, 7087, 1768, 63, 67, 869, 65, 411, 389, 2722, 7087, 1768, 63, 3576, 18, 15330, 5717, 288, 203, 5411, 389, 2722, 7087, 1768, 63, 67, 869, 65, 273, 389, 2722, 7087, 1768, 63, 3576, 18, 15330, 15533, 203, 3639, 289, 203, 203, 3639, 389, 23581, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 3639, 389, 2722, 7087, 1768, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 389, 869, 16, 11013, 951, 12, 3576, 18, 15330, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * ////IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * ////IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT 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; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "./IERC20.sol"; ////import "./extensions/IERC20Metadata.sol"; ////import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * ////IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _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()); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "./math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT 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; } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "./draft-IERC20Permit.sol"; ////import "../ERC20.sol"; ////import "../../../utils/cryptography/draft-EIP712.sol"; ////import "../../../utils/cryptography/ECDSA.sol"; ////import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../ERC20.sol"; ////import "../../../security/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../ERC20.sol"; ////import "../../../utils/Arrays.sol"; ////import "../../../utils/Counters.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract. * * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient * alternative consider {ERC20Votes}. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping(address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _getCurrentSnapshotId(); emit Snapshot(currentId); return currentId; } /** * @dev Get the current snapshotId */ function _getCurrentSnapshotId() internal view virtual returns (uint256) { return _currentSnapshotId.current(); } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _getCurrentSnapshotId(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../ERC20.sol"; ////import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @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); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT 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 override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } /** * SourceUnit: c:\Users\Jad\Documents\code\NFTC\nftc-monorepo\blockend\contracts\tokens\ArtCirculationToken.sol */ /////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.4.22 <0.9.0; /// @notice access control base classes ////import "../../node_modules/@openzeppelin/contracts/access/AccessControl.sol"; ////import "../../node_modules/@openzeppelin/contracts/access/Ownable.sol"; /// @notice ERC20 features base classes ////import "../../node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol"; ////import "../../node_modules/@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; ////import "../../node_modules/@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol"; ////import "../../node_modules/@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol"; ////import "../../node_modules/@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; /// @notice SafeMath library for uint calculations with overflow protections ////import "../../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Art Circulation Token * @notice ERC20-compliant+ smart contract for ACT token * @author Jad A. Jabbour @ NFT Contemporary **/ contract ArtCirculationToken is ERC20, ERC20Burnable, ERC20Snapshot, ERC20Pausable, AccessControl, Ownable, ERC20Permit { /// @notice using safe math for uints using SafeMath for uint; /// @notice contract version string private _version; /// @notice constant hashed roles for access control bytes32 public constant SNAPSHOT_ROLE = keccak256("SNAPSHOT_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @notice the fees as per-thousand from checques transactions uint private checquesFeesPerThousand; /** * @notice constructor **/ constructor() ERC20("ArtCirculationToken", "ACT") ERC20Permit("ArtCirculationToken") Ownable() { __ArtCirculationToken_init(_msgSender()); } /** * @notice internal initialize function for contract setup * @param admin address of the contract admin **/ function __ArtCirculationToken_init(address admin) internal{ _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(SNAPSHOT_ROLE, admin); _setupRole(PAUSER_ROLE, admin); _setupRole(MINTER_ROLE, admin); _mint(admin, 1000000000 * 10 ** decimals()); // 100 million tokens checquesFeesPerThousand = 5; _version = "1"; } /// @notice gets the contract version function version() public view returns (string memory) { return _version; } /** * @notice gets the checques fee rate per-thousand * @return uint checques fee-rate per-thousand **/ function getChecquesFees() external view returns (uint){ return checquesFeesPerThousand; } /** * @notice changes the fees collected on checques transfers * @param newFees the fee-rate per-thousand **/ function changeChecquesFees(uint newFees) external onlyOwner(){ checquesFeesPerThousand = newFees; } /** * @notice grants the minter role to the specified address * @param minter address **/ function grantMinter(address minter) public onlyRole(DEFAULT_ADMIN_ROLE) { grantRole(MINTER_ROLE, minter); } /** * @notice checks if address has the minter role * @param minter address **/ function isMinter(address minter) public view onlyRole(DEFAULT_ADMIN_ROLE) returns (bool){ return hasRole(MINTER_ROLE, minter); } /** * @notice revokes the minter role for the specified address * @param minter address **/ function revokeMinter(address minter) public onlyRole(DEFAULT_ADMIN_ROLE) { revokeRole(MINTER_ROLE, minter); } /** * @notice mints specific amount of tokens for specified address * @param to address * @param amount the amount of tokens to mint **/ function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) { _mint(to, amount); } /** * @notice grants the pauser role to a specified address * @param pauser address **/ function grantPauser(address pauser) public onlyRole(DEFAULT_ADMIN_ROLE) { grantRole(PAUSER_ROLE, pauser); } /** * @notice checks if address has the pauser role * @param pauser address **/ function isPauser(address pauser) public view onlyRole(DEFAULT_ADMIN_ROLE) returns (bool){ return hasRole(PAUSER_ROLE, pauser); } /** * @notice revokes the pauser role for the specified address * @param pauser address **/ function revokePauser(address pauser) public onlyRole(DEFAULT_ADMIN_ROLE) { revokeRole(PAUSER_ROLE, pauser); } /// @notice pauses the token contract function pause() public onlyRole(PAUSER_ROLE) { _pause(); } /// @notice unpauses the token contract function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } /** * @notice grants the snapshot role to a specified address * @param _snapshot address **/ function grantSnapshot(address _snapshot) public onlyRole(DEFAULT_ADMIN_ROLE) { grantRole(SNAPSHOT_ROLE, _snapshot); } /** * @notice checks if address has the snapshot role * @param _snapshot address **/ function isSnapshoter(address _snapshot) public view onlyRole(DEFAULT_ADMIN_ROLE) returns (bool){ return hasRole(SNAPSHOT_ROLE, _snapshot); } /** * @notice revokes the snapshot role for the specified address * @param _snapshot address **/ function revokeSnapshot(address _snapshot) public onlyRole(DEFAULT_ADMIN_ROLE) { revokeRole(SNAPSHOT_ROLE, _snapshot); } /// @notice takes a snapshot of the token contract function snapshot() public onlyRole(SNAPSHOT_ROLE) { _snapshot(); } /** * @notice cashes a list of checques as signed permits for the beneficiary * @param spender address of beneficiary * @param owners address list of checques signatories * @param values the values transfered through the checques * @param deadlines the deadline for cashing in the checques * @param vs signatures * @param rs signatures * @param ss signatures */ function cashChecques( address spender, address[] memory owners, uint256[] memory values, uint256[] memory deadlines, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss ) external { /// @notice information arity match check require( owners.length == values.length /* solium-disable-line */ && owners.length == deadlines.length && owners.length == vs.length && owners.length == rs.length && owners.length == ss.length, "ArtCirculationToken:cashChecques:: INFORMATION_ARITY_MISMATCH"); /// @notice loop through permit-checques list and cash them for (uint i = 0;i < owners.length;i++){ cashChecque(owners[i], spender, values[i], deadlines[i], vs[i], rs[i], ss[i]); } } /** * @notice cashes the checque as signed permit for the beneficiary * @param owner address of checque signatory * @param spender address of beneficiary * @param value the value transfered through the checque * @param deadline the deadline for cashing in the checque * @param v signature * @param r signature * @param s signature **/ function cashChecque( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { /// @notice msg.sender should be same as spender address require(spender == _msgSender(), 'ArtCirculationToken:cashChecque:: INVALID_SPENDER_ADDRESS'); /// @notice calculate contract fee from checques amount uint fee = value.mul(checquesFeesPerThousand)/1000; /// @notice permit and transfer funds permit(owner, spender, value, deadline, v, r, s); transferFrom(owner, spender, value.sub(fee)); /// @notice burn contract fee tokens _burn(owner, fee); } /** * @notice before transfer function hook * @param from address sending the tokens * @param to address receiving the tokens * @param amount amount of tokens being transfered **/ function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override(ERC20, ERC20Snapshot, ERC20Pausable) { /// @notice call to parent before transfer hook super._beforeTokenTransfer(from, to, amount); } }
* @dev ERC20 token with pausable token transfers, minting and burning. Useful for scenarios such as preventing trades until the end of an evaluation period, or having an emergency switch for freezing all token transfers in the event of a large bug./
abstract contract ERC20Pausable is ERC20, Pausable { function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } }
372,271
[ 1, 654, 39, 3462, 1147, 598, 6790, 16665, 1147, 29375, 16, 312, 474, 310, 471, 18305, 310, 18, 19256, 364, 22456, 4123, 487, 5309, 310, 1284, 5489, 3180, 326, 679, 434, 392, 9873, 3879, 16, 578, 7999, 392, 801, 24530, 1620, 364, 4843, 94, 310, 777, 1147, 29375, 316, 326, 871, 434, 279, 7876, 7934, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 17801, 6835, 4232, 39, 3462, 16507, 16665, 353, 4232, 39, 3462, 16, 21800, 16665, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 2398, 203, 203, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 3639, 2583, 12, 5, 8774, 3668, 9334, 315, 654, 39, 3462, 16507, 16665, 30, 1147, 7412, 1323, 17781, 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, -100, -100, -100 ]
// 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; } } abstract contract Claimable is Context { address private _owner; address public pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event NewPendingOwner(address indexed owner); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(_msgSender() == owner(), "Ownable: caller is not the owner"); _; } modifier onlyPendingOwner() { require(_msgSender() == pendingOwner); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner(), address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(pendingOwner == address(0)); pendingOwner = newOwner; emit NewPendingOwner(newOwner); } function cancelTransferOwnership() public onlyOwner { require(pendingOwner != address(0)); delete pendingOwner; emit NewPendingOwner(address(0)); } function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner(), pendingOwner); _owner = pendingOwner; delete pendingOwner; } } 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 ); } interface IFujiOracle { function getPriceOf( address _collateralAsset, address _borrowAsset, uint8 _decimals ) external view returns (uint256); } /** * @title Errors library * @author Fuji * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = Validation Logic 100 series * - MATH = Math libraries 200 series * - RF = Refinancing 300 series * - VLT = vault 400 series * - SP = Special 900 series */ library Errors { //Errors string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128 string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match. string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155 string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract. string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid. string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer. string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved. string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27) string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close. string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest. string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance. string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed string public constant VL_ERC1155_NOT_TRANSFERABLE = "128"; // ERC1155: Not Transferable string public constant VL_SWAP_SLIPPAGE_LIMIT_EXCEED = "129"; // ERC1155: Not Transferable string public constant VL_ZERO_ADDR = "130"; // Zero Address string public constant MATH_DIVISION_BY_ZERO = "201"; string public constant MATH_ADDITION_OVERFLOW = "202"; string public constant MATH_MULTIPLICATION_OVERFLOW = "203"; string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0 string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault string public constant ORACLE_INVALID_LENGTH = "501"; // The assets length and price feeds length doesn't match string public constant ORACLE_NONE_PRICE_FEED = "502"; // The price feed is not found } contract FujiOracle is IFujiOracle, Claimable { // mapping from asset address to its price feed oracle in USD - decimals: 8 mapping(address => address) public usdPriceFeeds; constructor(address[] memory _assets, address[] memory _priceFeeds) Claimable() { require(_assets.length == _priceFeeds.length, Errors.ORACLE_INVALID_LENGTH); for (uint256 i = 0; i < _assets.length; i++) { usdPriceFeeds[_assets[i]] = _priceFeeds[i]; } } function setPriceFeed(address _asset, address _priceFeed) public onlyOwner { usdPriceFeeds[_asset] = _priceFeed; } /// @dev Calculates the exchange rate n given decimals (_borrowAsset / _collateralAsset Exchange Rate) /// @param _collateralAsset the collateral asset, zero-address for USD /// @param _borrowAsset the borrow asset, zero-address for USD /// @param _decimals the decimals of the price output /// @return price The exchange rate of the given assets pair function getPriceOf( address _collateralAsset, address _borrowAsset, uint8 _decimals ) external view override returns (uint256 price) { price = 10**uint256(_decimals); if (_borrowAsset != address(0)) { price = price * _getUSDPrice(_borrowAsset); } else { price = price * (10**8); } if (_collateralAsset != address(0)) { price = price / _getUSDPrice(_collateralAsset); } else { price = price / (10**8); } } /// @dev Calculates the USD price of asset /// @param _asset the asset address /// @return price USD price of the give asset function _getUSDPrice(address _asset) internal view returns (uint256 price) { require(usdPriceFeeds[_asset] != address(0), Errors.ORACLE_NONE_PRICE_FEED); (, int256 latestPrice, , , ) = AggregatorV3Interface(usdPriceFeeds[_asset]).latestRoundData(); price = uint256(latestPrice); } }
index overflows uint128
string public constant VL_INDEX_OVERFLOW = "100";
182,091
[ 1, 1615, 9391, 87, 2254, 10392, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 533, 1071, 5381, 776, 48, 67, 9199, 67, 12959, 17430, 273, 315, 6625, 14432, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../balancer/BFactory.sol"; import "../libraries/SafeMathUint256.sol"; import "./AbstractMarketFactoryV3.sol"; import "../balancer/BNum.sol"; contract AMMFactory is BNum { using SafeMathUint256 for uint256; uint256 private constant MAX_UINT = 2**256 - 1; uint256 private constant MIN_INITIAL_LIQUIDITY = BONE * 100; BFactory public bFactory; // MarketFactory => Market => BPool mapping(address => mapping(uint256 => BPool)) public pools; uint256 fee; event PoolCreated( address pool, address indexed marketFactory, uint256 indexed marketId, address indexed creator, address lpTokenRecipient ); event LiquidityChanged( address indexed marketFactory, uint256 indexed marketId, address indexed user, address recipient, // from the perspective of the user. e.g. collateral is negative when adding liquidity int256 collateral, int256 lpTokens, uint256[] sharesReturned ); event SharesSwapped( address indexed marketFactory, uint256 indexed marketId, address indexed user, uint256 outcome, // from the perspective of the user. e.g. collateral is negative when buying int256 collateral, int256 shares, uint256 price ); constructor(BFactory _bFactory, uint256 _fee) { bFactory = _bFactory; fee = _fee; } function createPool( AbstractMarketFactoryV3 _marketFactory, uint256 _marketId, uint256 _initialLiquidity, address _lpTokenRecipient ) public returns (uint256) { require(pools[address(_marketFactory)][_marketId] == BPool(0), "Pool already created"); AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId); uint256 _sets = _marketFactory.calcShares(_initialLiquidity); // Comparing to sets because sets are normalized to 10e18. require(_sets >= MIN_INITIAL_LIQUIDITY, "Initial liquidity must be at least 100 collateral."); // Turn collateral into shares IERC20Full _collateral = _marketFactory.collateral(); require( _collateral.allowance(msg.sender, address(this)) >= _initialLiquidity, "insufficient collateral allowance for initial liquidity" ); _collateral.transferFrom(msg.sender, address(this), _initialLiquidity); _collateral.approve(address(_marketFactory), MAX_UINT); _marketFactory.mintShares(_marketId, _sets, address(this)); // Create pool BPool _pool = bFactory.newBPool(); // Add each outcome to the pool. Collateral is NOT added. for (uint256 i = 0; i < _market.shareTokens.length; i++) { OwnedERC20 _token = _market.shareTokens[i]; _token.approve(address(_pool), MAX_UINT); _pool.bind(address(_token), _sets, _market.initialOdds[i]); } // Set the swap fee. _pool.setSwapFee(fee); // Finalize pool setup _pool.finalize(); pools[address(_marketFactory)][_marketId] = _pool; // Pass along LP tokens for initial liquidity uint256 _lpTokenBalance = _pool.balanceOf(address(this)) - (BONE / 1000); // Burn (BONE / 1000) lp tokens to prevent the bpool from locking up. When all liquidity is removed. _pool.transfer(address(0x0), (BONE / 1000)); _pool.transfer(_lpTokenRecipient, _lpTokenBalance); uint256[] memory _balances = new uint256[](_market.shareTokens.length); for (uint256 i = 0; i < _market.shareTokens.length; i++) { _balances[i] = 0; } emit PoolCreated(address(_pool), address(_marketFactory), _marketId, msg.sender, _lpTokenRecipient); emit LiquidityChanged( address(_marketFactory), _marketId, msg.sender, _lpTokenRecipient, -int256(_initialLiquidity), int256(_lpTokenBalance), _balances ); return _lpTokenBalance; } function addLiquidity( AbstractMarketFactoryV3 _marketFactory, uint256 _marketId, uint256 _collateralIn, uint256 _minLPTokensOut, address _lpTokenRecipient ) public returns (uint256 _poolAmountOut, uint256[] memory _balances) { BPool _pool = pools[address(_marketFactory)][_marketId]; require(_pool != BPool(0), "Pool needs to be created"); AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId); // Turn collateral into shares IERC20Full _collateral = _marketFactory.collateral(); _collateral.transferFrom(msg.sender, address(this), _collateralIn); _collateral.approve(address(_marketFactory), MAX_UINT); uint256 _sets = _marketFactory.calcShares(_collateralIn); _marketFactory.mintShares(_marketId, _sets, address(this)); // Find poolAmountOut _poolAmountOut = MAX_UINT; { uint256 _totalSupply = _pool.totalSupply(); uint256[] memory _maxAmountsIn = new uint256[](_market.shareTokens.length); for (uint256 i = 0; i < _market.shareTokens.length; i++) { _maxAmountsIn[i] = _sets; OwnedERC20 _token = _market.shareTokens[i]; uint256 _bPoolTokenBalance = _pool.getBalance(address(_token)); // This is the result the following when solving for poolAmountOut: // uint256 ratio = bdiv(poolAmountOut, poolTotal); // uint256 tokenAmountIn = bmul(ratio, bal); uint256 _tokenPoolAmountOut = (((((_sets * BONE) - (BONE / 2)) * _totalSupply) / _bPoolTokenBalance) - (_totalSupply / 2)) / BONE; if (_tokenPoolAmountOut < _poolAmountOut) { _poolAmountOut = _tokenPoolAmountOut; } } _pool.joinPool(_poolAmountOut, _maxAmountsIn); } require(_poolAmountOut >= _minLPTokensOut, "Would not have received enough LP tokens"); _pool.transfer(_lpTokenRecipient, _poolAmountOut); // Transfer the remaining shares back to _lpTokenRecipient. _balances = new uint256[](_market.shareTokens.length); for (uint256 i = 0; i < _market.shareTokens.length; i++) { OwnedERC20 _token = _market.shareTokens[i]; _balances[i] = _token.balanceOf(address(this)); if (_balances[i] > 0) { _token.transfer(_lpTokenRecipient, _balances[i]); } } emit LiquidityChanged( address(_marketFactory), _marketId, msg.sender, _lpTokenRecipient, -int256(_collateralIn), int256(_poolAmountOut), _balances ); } function removeLiquidity( AbstractMarketFactoryV3 _marketFactory, uint256 _marketId, uint256 _lpTokensIn, uint256 _minCollateralOut, address _collateralRecipient ) public returns (uint256 _collateralOut, uint256[] memory _balances) { BPool _pool = pools[address(_marketFactory)][_marketId]; require(_pool != BPool(0), "Pool needs to be created"); AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId); _pool.transferFrom(msg.sender, address(this), _lpTokensIn); uint256[] memory exitPoolEstimate; { uint256[] memory minAmountsOut = new uint256[](_market.shareTokens.length); exitPoolEstimate = _pool.calcExitPool(_lpTokensIn, minAmountsOut); _pool.exitPool(_lpTokensIn, minAmountsOut); } // Find the number of sets to sell. uint256 _setsToSell = MAX_UINT; for (uint256 i = 0; i < _market.shareTokens.length; i++) { uint256 _acquiredTokenBalance = exitPoolEstimate[i]; if (_acquiredTokenBalance < _setsToSell) _setsToSell = _acquiredTokenBalance; } // Must be a multiple of share factor. _setsToSell = (_setsToSell / _marketFactory.shareFactor()) * _marketFactory.shareFactor(); bool _resolved = _marketFactory.isMarketResolved(_marketId); if (_resolved) { _collateralOut = _marketFactory.claimWinnings(_marketId, _collateralRecipient); } else { _collateralOut = _marketFactory.burnShares(_marketId, _setsToSell, _collateralRecipient); } require(_collateralOut > _minCollateralOut, "Amount of collateral returned too low."); // Transfer the remaining shares back to _collateralRecipient. _balances = new uint256[](_market.shareTokens.length); for (uint256 i = 0; i < _market.shareTokens.length; i++) { OwnedERC20 _token = _market.shareTokens[i]; if (_resolved && _token == _market.winner) continue; // all winning shares claimed when market is resolved _balances[i] = exitPoolEstimate[i] - _setsToSell; if (_balances[i] > 0) { _token.transfer(_collateralRecipient, _balances[i]); } } emit LiquidityChanged( address(_marketFactory), _marketId, msg.sender, _collateralRecipient, int256(_collateralOut), -int256(_lpTokensIn), _balances ); } function buy( AbstractMarketFactoryV3 _marketFactory, uint256 _marketId, uint256 _outcome, uint256 _collateralIn, uint256 _minTokensOut ) external returns (uint256) { BPool _pool = pools[address(_marketFactory)][_marketId]; require(_pool != BPool(0), "Pool needs to be created"); AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId); IERC20Full _collateral = _marketFactory.collateral(); _collateral.transferFrom(msg.sender, address(this), _collateralIn); uint256 _sets = _marketFactory.calcShares(_collateralIn); _marketFactory.mintShares(_marketId, _sets, address(this)); uint256 _totalDesiredOutcome = _sets; { OwnedERC20 _desiredToken = _market.shareTokens[_outcome]; for (uint256 i = 0; i < _market.shareTokens.length; i++) { if (i == _outcome) continue; OwnedERC20 _token = _market.shareTokens[i]; (uint256 _acquiredToken, ) = _pool.swapExactAmountIn(address(_token), _sets, address(_desiredToken), 0, MAX_UINT); _totalDesiredOutcome += _acquiredToken; } require(_totalDesiredOutcome >= _minTokensOut, "Slippage exceeded"); _desiredToken.transfer(msg.sender, _totalDesiredOutcome); } emit SharesSwapped( address(_marketFactory), _marketId, msg.sender, _outcome, -int256(_collateralIn), int256(_totalDesiredOutcome), bdiv(_sets, _totalDesiredOutcome) ); return _totalDesiredOutcome; } function sellForCollateral( AbstractMarketFactoryV3 _marketFactory, uint256 _marketId, uint256 _outcome, uint256[] memory _shareTokensIn, uint256 _minSetsOut ) external returns (uint256) { BPool _pool = pools[address(_marketFactory)][_marketId]; require(_pool != BPool(0), "Pool needs to be created"); AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId); uint256 _setsOut = MAX_UINT; uint256 _totalUndesiredTokensIn = 0; for (uint256 i = 0; i < _market.shareTokens.length; i++) { _totalUndesiredTokensIn += _shareTokensIn[i]; } { _market.shareTokens[_outcome].transferFrom(msg.sender, address(this), _totalUndesiredTokensIn); _market.shareTokens[_outcome].approve(address(_pool), MAX_UINT); for (uint256 i = 0; i < _market.shareTokens.length; i++) { if (i == _outcome) continue; OwnedERC20 _token = _market.shareTokens[i]; (uint256 tokenAmountOut, ) = _pool.swapExactAmountIn( address(_market.shareTokens[_outcome]), _shareTokensIn[i], address(_token), 0, MAX_UINT ); //Ensure tokenAmountOut is a multiple of shareFactor. tokenAmountOut = (tokenAmountOut / _marketFactory.shareFactor()) * _marketFactory.shareFactor(); if (tokenAmountOut < _setsOut) _setsOut = tokenAmountOut; } require(_setsOut >= _minSetsOut, "Minimum sets not available."); _marketFactory.burnShares(_marketId, _setsOut, msg.sender); } // Transfer undesired token balance back. for (uint256 i = 0; i < _market.shareTokens.length; i++) { OwnedERC20 _token = _market.shareTokens[i]; uint256 _balance = _token.balanceOf(address(this)); if (_balance > 0) { _token.transfer(msg.sender, _balance); } } uint256 _collateralOut = _marketFactory.calcCost(_setsOut); emit SharesSwapped( address(_marketFactory), _marketId, msg.sender, _outcome, int256(_collateralOut), -int256(_totalUndesiredTokensIn), bdiv(_setsOut, _totalUndesiredTokensIn) ); return _collateralOut; } // Returns an array of token values for the outcomes of the market, relative to the first outcome. // So the first outcome is 10**18 and all others are higher or lower. // Prices can be derived due to the fact that the total of all outcome shares equals one collateral, possibly with a scaling factor, function tokenRatios(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId) external view returns (uint256[] memory) { BPool _pool = pools[address(_marketFactory)][_marketId]; // Pool does not exist. Do not want to revert because multicall. if (_pool == BPool(0)) { return new uint256[](0); } AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId); address _basisToken = address(_market.shareTokens[0]); uint256[] memory _ratios = new uint256[](_market.shareTokens.length); _ratios[0] = 10**18; for (uint256 i = 1; i < _market.shareTokens.length; i++) { uint256 _price = _pool.getSpotPrice(_basisToken, address(_market.shareTokens[i])); _ratios[i] = _price; } return _ratios; } function getPoolBalances(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId) external view returns (uint256[] memory) { BPool _pool = pools[address(_marketFactory)][_marketId]; // Pool does not exist. Do not want to revert because multicall. if (_pool == BPool(0)) { return new uint256[](0); } address[] memory _tokens = _pool.getCurrentTokens(); uint256[] memory _balances = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { _balances[i] = _pool.getBalance(_tokens[i]); } return _balances; } function getPoolWeights(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId) external view returns (uint256[] memory) { BPool _pool = pools[address(_marketFactory)][_marketId]; // Pool does not exist. Do not want to revert because multicall. if (_pool == BPool(0)) { return new uint256[](0); } address[] memory _tokens = _pool.getCurrentTokens(); uint256[] memory _weights = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { _weights[i] = _pool.getDenormalizedWeight(_tokens[i]); } return _weights; } function getSwapFee(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId) external view returns (uint256) { BPool _pool = pools[address(_marketFactory)][_marketId]; return _pool.getSwapFee(); } function getPoolTokenBalance( AbstractMarketFactoryV3 _marketFactory, uint256 _marketId, address _user ) external view returns (uint256) { BPool _pool = pools[address(_marketFactory)][_marketId]; return _pool.balanceOf(_user); } function getPool(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId) external view returns (BPool) { return pools[address(_marketFactory)][_marketId]; } }
Finalize pool setup
_pool.finalize();
12,875,563
[ 1, 7951, 554, 2845, 3875, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 6011, 18, 30343, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./external/@openzeppelin/token/ERC20/extensions/IERC20Metadata.sol"; import "./external/spool-core/SpoolOwnable.sol"; import "./interfaces/IVoSPOOL.sol"; /* ========== STRUCTS ========== */ /** * @notice global tranche struct * @dev used so it can be passed through functions as a struct * @member amount amount minted in tranche */ struct Tranche { uint48 amount; } /** * @notice global tranches struct holding 5 tranches * @dev made to pack multiple tranches in one word * @member zero tranche in pack at position 0 * @member one tranche in pack at position 1 * @member two tranche in pack at position 2 * @member three tranche in pack at position 3 * @member four tranche in pack at position 4 */ struct GlobalTranches { Tranche zero; Tranche one; Tranche two; Tranche three; Tranche four; } /** * @notice user tranche struct * @dev struct holds users minted amount at tranche at index * @member amount users amount minted at tranche * @member index tranche index */ struct UserTranche { uint48 amount; uint16 index; } /** * @notice user tranches struct, holding 4 user tranches * @dev made to pack multiple tranches in one word * @member zero user tranche in pack at position 0 * @member one user tranche in pack at position 1 * @member two user tranche in pack at position 2 * @member three user tranche in pack at position 3 */ struct UserTranches { UserTranche zero; UserTranche one; UserTranche two; UserTranche three; } /** * @title Spool DAO Voting Token Implementation * * @notice The voting SPOOL pseudo-ERC20 Implementation * * An untransferable token implementation meant to be used by the * Spool DAO to mint the voting equivalent of the staked token. * * @dev * Users voting power consists of instant and gradual (maturing) voting power. * voSPOOL contract assumes voting power comes from vesting or staking SPOOL tokens. * As SPOOL tokens have a maximum supply of 210,000,000 * 10**18, we consider this * limitation when storing data (e.g. storing amount divided by 10**12) to save on gas. * * Instant voting power can be used in the full amount as soon as minted. * * Gradual voting power: * Matures linearly over 156 weeks (3 years) up to the minted amount. * If a user burns gradual voting power, all accumulated voting power is * reset to zero. In case there is some amount left, it'll take another 3 * years to achieve fully-matured power. Only gradual voting power is reset * and not instant one. * Gradual voting power updates at every new tranche, which lasts one week. * * Contract consists of: * - CONSTANTS * - STATE VARIABLES * - CONSTRUCTOR * - IERC20 FUNCTIONS * - INSTANT POWER FUNCTIONS * - GRADUAL POWER FUNCTIONS * - GRADUAL POWER: VIEW FUNCTIONS * - GRADUAL POWER: MINT FUNCTIONS * - GRADUAL POWER: BURN FUNCTIONS * - GRADUAL POWER: UPDATE GLOBAL FUNCTIONS * - GRADUAL POWER: UPDATE USER FUNCTIONS * - GRADUAL POWER: GLOBAL HELPER FUNCTIONS * - GRADUAL POWER: USER HELPER FUNCTIONS * - GRADUAL POWER: HELPER FUNCTIONS * - OWNER FUNCTIONS * - RESTRICTION FUNCTIONS * - MODIFIERS */ contract VoSPOOL is SpoolOwnable, IVoSPOOL, IERC20Metadata { /* ========== CONSTANTS ========== */ /// @notice trim size value of the mint amount /// @dev we trim gradual mint amount by `TRIM_SIZE`, so it takes less storage uint256 private constant TRIM_SIZE = 10**12; /// @notice number of tranche amounts stored in one 256bit word uint256 private constant TRANCHES_PER_WORD = 5; /// @notice duration of one tranche uint256 public constant TRANCHE_TIME = 1 weeks; /// @notice amount of tranches to mature to full power uint256 public constant FULL_POWER_TRANCHES_COUNT = 52 * 3; /// @notice time until gradual power is fully-matured /// @dev full power time is 156 weeks (approximately 3 years) uint256 public constant FULL_POWER_TIME = TRANCHE_TIME * FULL_POWER_TRANCHES_COUNT; /// @notice Token name full name string public constant name = "Spool DAO Voting Token"; /// @notice Token symbol string public constant symbol = "voSPOOL"; /// @notice Token decimals uint8 public constant decimals = 18; /* ========== STATE VARIABLES ========== */ /// @notice tranche time for index 1 uint256 public immutable firstTrancheStartTime; /// @notice mapping holding instant minting privileges for addresses mapping(address => bool) public minters; /// @notice mapping holding gradual minting privileges for addresses mapping(address => bool) public gradualMinters; /// @notice total instant voting power uint256 public totalInstantPower; /// @notice user instant voting power mapping(address => uint256) public userInstantPower; /// @notice global gradual power values GlobalGradual private _globalGradual; /// @notice global tranches /// @dev mapping tranche index to a group of tranches (5 tranches per word) mapping(uint256 => GlobalTranches) public indexedGlobalTranches; /// @notice user gradual power values mapping(address => UserGradual) private _userGraduals; /// @notice user tranches /// @dev mapping users to its tranches mapping(address => mapping(uint256 => UserTranches)) public userTranches; /* ========== CONSTRUCTOR ========== */ /** * @notice Sets the value of _spoolOwner and first tranche end time * @dev With `_firstTrancheEndTime` you can set when the first tranche time * finishes and essentially users minted get the first foting power. * e.g. if we set it to Sunday 10pm and tranche time is 1 week, * all new tranches in the future will finish on Sunday 10pm and new * voSPOOL power will mature and be accrued. * * Requirements: * * - first tranche time must be in the future * - first tranche time must must be less than full tranche time in the future * * @param _spoolOwner address of spool owner contract * @param _firstTrancheEndTime first tranche end time after the deployment */ constructor(ISpoolOwner _spoolOwner, uint256 _firstTrancheEndTime) SpoolOwnable(_spoolOwner) { require( _firstTrancheEndTime > block.timestamp, "voSPOOL::constructor: First tranche end time must be in the future" ); require( _firstTrancheEndTime < block.timestamp + TRANCHE_TIME, "voSPOOL::constructor: First tranche end time must be less than full tranche time in the future" ); unchecked { // set first tranche start time firstTrancheStartTime = _firstTrancheEndTime - TRANCHE_TIME; } } /* ========== IERC20 FUNCTIONS ========== */ /** * @notice Returns current total voting power */ function totalSupply() external view override returns (uint256) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return totalInstantPower + _getTotalGradualVotingPower(global); } /** * @notice Returns current user total voting power */ function balanceOf(address account) external view override returns (uint256) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(account); return userInstantPower[account] + _getUserGradualVotingPower(_userGradual); } /** * @dev Execution of function is prohibited to disallow token movement */ function transfer(address, uint256) external pure override returns (bool) { revert("voSPOOL::transfer: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function transferFrom( address, address, uint256 ) external pure override returns (bool) { revert("voSPOOL::transferFrom: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function approve(address, uint256) external pure override returns (bool) { revert("voSPOOL::approve: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function allowance(address, address) external pure override returns (uint256) { revert("voSPOOL::allowance: Prohibited Action"); } /* ========== INSTANT POWER FUNCTIONS ========== */ /** * @notice Mints the provided amount as instant voting power. * * Requirements: * * - the caller must be the autorized * * @param to mint to user * @param amount mint amount */ function mint(address to, uint256 amount) external onlyMinter { totalInstantPower += amount; unchecked { userInstantPower[to] += amount; } emit Minted(to, amount); } /** * @notice Burns the provided amount of instant power from the specified user. * @dev only instant power is removed, gradual power stays the same * * Requirements: * * - the caller must be the instant minter * - the user must posses at least the burning `amount` of instant voting power amount * * @param from burn from user * @param amount burn amount */ function burn(address from, uint256 amount) external onlyMinter { require(userInstantPower[from] >= amount, "voSPOOL:burn: User instant power balance too low"); unchecked { userInstantPower[from] -= amount; totalInstantPower -= amount; } emit Burned(from, amount); } /* ========== GRADUAL POWER FUNCTIONS ========== */ /* ---------- GRADUAL POWER: VIEW FUNCTIONS ---------- */ /** * @notice returns updated total gradual voting power (fully-matured and maturing) * * @return totalGradualVotingPower total gradual voting power (fully-matured + maturing) */ function getTotalGradualVotingPower() external view returns (uint256) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return _getTotalGradualVotingPower(global); } /** * @notice returns updated global gradual struct * * @return global updated global gradual struct */ function getGlobalGradual() external view returns (GlobalGradual memory) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return global; } /** * @notice returns not updated global gradual struct * * @return global updated global gradual struct */ function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory) { return _globalGradual; } /** * @notice returns updated user gradual voting power (fully-matured and maturing) * * @param user address holding voting power * @return userGradualVotingPower user gradual voting power (fully-matured + maturing) */ function getUserGradualVotingPower(address user) external view returns (uint256) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(user); return _getUserGradualVotingPower(_userGradual); } /** * @notice returns updated user gradual struct * * @param user user address * @return _userGradual user updated gradual struct */ function getUserGradual(address user) external view returns (UserGradual memory) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(user); return _userGradual; } /** * @notice returns not updated user gradual struct * * @param user user address * @return _userGradual user updated gradual struct */ function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory) { return _userGraduals[user]; } /** * @notice Returns current active tranche index * * @return trancheIndex current tranche index */ function getCurrentTrancheIndex() public view returns (uint16) { return _getTrancheIndex(block.timestamp); } /** * @notice Returns tranche index based on `time` * @dev `time` can be any time inside the tranche * * Requirements: * * - `time` must be equal to more than first tranche time * * @param time tranche time time to get the index for * @return trancheIndex tranche index at `time` */ function getTrancheIndex(uint256 time) external view returns (uint256) { require( time >= firstTrancheStartTime, "voSPOOL::getTrancheIndex: Time must be more or equal to the first tranche time" ); return _getTrancheIndex(time); } /** * @notice Returns tranche index based at time * * @param time unix time * @return trancheIndex tranche index at `time` */ function _getTrancheIndex(uint256 time) private view returns (uint16) { unchecked { return uint16(((time - firstTrancheStartTime) / TRANCHE_TIME) + 1); } } /** * @notice Returns next tranche end time * * @return trancheEndTime end time for next tranche */ function getNextTrancheEndTime() external view returns (uint256) { return getTrancheEndTime(getCurrentTrancheIndex()); } /** * @notice Returns tranche end time for tranche index * * @param trancheIndex tranche index * @return trancheEndTime end time for `trancheIndex` */ function getTrancheEndTime(uint256 trancheIndex) public view returns (uint256) { return firstTrancheStartTime + trancheIndex * TRANCHE_TIME; } /** * @notice Returns last finished tranche index * * @return trancheIndex last finished tranche index */ function getLastFinishedTrancheIndex() public view returns (uint16) { unchecked { return getCurrentTrancheIndex() - 1; } } /* ---------- GRADUAL POWER: MINT FUNCTIONS ---------- */ /** * @notice Mints the provided amount of tokens to the specified user to gradually mature up to the amount. * @dev Saves the amount to tranche user index, so the voting power starts maturing. * * Requirements: * * - the caller must be the autorized * * @param to gradual mint to user * @param amount gradual mint amount */ function mintGradual(address to, uint256 amount) external onlyGradualMinter updateGradual updateGradualUser(to) { uint48 trimmedAmount = _trim(amount); _mintGradual(to, trimmedAmount); emit GradualMinted(to, amount); } /** * @notice Mints the provided amount of tokens to the specified user to gradually mature up to the amount. * @dev Saves the amount to tranche user index, so the voting power starts maturing. * * @param to gradual mint to user * @param trimmedAmount gradual mint trimmed amount */ function _mintGradual(address to, uint48 trimmedAmount) private { if (trimmedAmount == 0) { return; } UserGradual memory _userGradual = _userGraduals[to]; // add new maturing amount to user and global amount _userGradual.maturingAmount += trimmedAmount; _globalGradual.totalMaturingAmount += trimmedAmount; // add maturing amount to user tranche UserTranche memory latestTranche = _getUserTranche(to, _userGradual.latestTranchePosition); uint16 currentTrancheIndex = getCurrentTrancheIndex(); bool isFirstGradualMint = !_hasTranches(_userGradual); // if latest user tranche is not current index, update latest // user can have first mint or last tranche deposited is finished if (isFirstGradualMint || latestTranche.index < currentTrancheIndex) { UserTranchePosition memory nextTranchePosition = _getNextUserTranchePosition( _userGradual.latestTranchePosition ); // if first time gradual minting set oldest tranche position if (isFirstGradualMint) { _userGradual.oldestTranchePosition = nextTranchePosition; } // update latest tranche _userGradual.latestTranchePosition = nextTranchePosition; latestTranche = UserTranche(trimmedAmount, currentTrancheIndex); } else { // if user already minted in current tranche, add additional amount latestTranche.amount += trimmedAmount; } // update global tranche amount _addGlobalTranche(latestTranche.index, trimmedAmount); // store updated user values _setUserTranche(to, _userGradual.latestTranchePosition, latestTranche); _userGraduals[to] = _userGradual; } /** * @notice add `amount` to global tranche `index` * * @param index tranche index * @param amount amount to add */ function _addGlobalTranche(uint256 index, uint48 amount) private { Tranche storage tranche = _getTranche(index); tranche.amount += amount; } /** * @notice sets updated `user` `tranche` at position * * @param user user address to set tranche * @param userTranchePosition position to set the `tranche` at * @param tranche updated `user` tranche */ function _setUserTranche( address user, UserTranchePosition memory userTranchePosition, UserTranche memory tranche ) private { UserTranches storage _userTranches = userTranches[user][userTranchePosition.arrayIndex]; if (userTranchePosition.position == 0) { _userTranches.zero = tranche; } else if (userTranchePosition.position == 1) { _userTranches.one = tranche; } else if (userTranchePosition.position == 2) { _userTranches.two = tranche; } else { _userTranches.three = tranche; } } /* ---------- GRADUAL POWER: BURN FUNCTIONS ---------- */ /** * @notice Burns the provided amount of gradual power from the specified user. * @dev User loses all matured power accumulated till now. * Voting power starts maturing from the start if there is any amount left. * * Requirements: * * - the caller must be the gradual minter * * @param from burn from user * @param amount burn amount * @param burnAll true to burn all user amount */ function burnGradual( address from, uint256 amount, bool burnAll ) external onlyGradualMinter updateGradual updateGradualUser(from) { UserGradual memory _userGradual = _userGraduals[from]; uint48 userTotalGradualAmount = _userGradual.maturedVotingPower + _userGradual.maturingAmount; // remove user matured power if (_userGradual.maturedVotingPower > 0) { _globalGradual.totalMaturedVotingPower -= _userGradual.maturedVotingPower; _userGradual.maturedVotingPower = 0; } // remove user maturing if (_userGradual.maturingAmount > 0) { _globalGradual.totalMaturingAmount -= _userGradual.maturingAmount; _userGradual.maturingAmount = 0; } // remove user unmatured power if (_userGradual.rawUnmaturedVotingPower > 0) { _globalGradual.totalRawUnmaturedVotingPower -= _userGradual.rawUnmaturedVotingPower; _userGradual.rawUnmaturedVotingPower = 0; } // if user has any tranches, remove all of them from user and global if (_hasTranches(_userGradual)) { uint256 fromIndex = _userGradual.oldestTranchePosition.arrayIndex; uint256 toIndex = _userGradual.latestTranchePosition.arrayIndex; // loop over user tranches and delete all of them for (uint256 i = fromIndex; i <= toIndex; i++) { // delete from global tranches _deleteUserTranchesFromGlobal(userTranches[from][i]); // delete user tranches delete userTranches[from][i]; } } // reset oldest tranche (meaning user has no tranches) _userGradual.oldestTranchePosition = UserTranchePosition(0, 0); // apply changes to storage _userGraduals[from] = _userGradual; emit GradualBurned(from, amount, burnAll); // if we don't burn all gradual amount, restart maturing if (!burnAll) { uint48 trimmedAmount = _trimRoundUp(amount); // if user still has some amount left, mint gradual from start if (userTotalGradualAmount > trimmedAmount) { unchecked { uint48 userAmountLeft = userTotalGradualAmount - trimmedAmount; // mint amount left _mintGradual(from, userAmountLeft); } } } } /** * @notice remove user tranches amounts from global tranches * @dev remove for all four user tranches in the struct * * @param _userTranches user tranches */ function _deleteUserTranchesFromGlobal(UserTranches memory _userTranches) private { _removeUserTrancheFromGlobal(_userTranches.zero); _removeUserTrancheFromGlobal(_userTranches.one); _removeUserTrancheFromGlobal(_userTranches.two); _removeUserTrancheFromGlobal(_userTranches.three); } /** * @notice remove user tranche amount from global tranche * * @param userTranche user tranche */ function _removeUserTrancheFromGlobal(UserTranche memory userTranche) private { if (userTranche.amount > 0) { Tranche storage tranche = _getTranche(userTranche.index); tranche.amount -= userTranche.amount; } } /* ---------- GRADUAL POWER: UPDATE GLOBAL FUNCTIONS ---------- */ /** * @notice updates global gradual voting power * @dev * * Requirements: * * - the caller must be the gradual minter */ function updateVotingPower() external override onlyGradualMinter { _updateGradual(); } /** * @notice updates global gradual voting power * @dev updates only if changes occured */ function _updateGradual() private { (GlobalGradual memory global, bool didUpdate) = _getUpdatedGradual(); if (didUpdate) { _globalGradual = global; emit GlobalGradualUpdated( global.lastUpdatedTrancheIndex, global.totalMaturedVotingPower, global.totalMaturingAmount, global.totalRawUnmaturedVotingPower ); } } /** * @notice returns updated global gradual values * @dev the update is in-memory * * @return global updated GlobalGradual struct * @return didUpdate flag if `global` was updated */ function _getUpdatedGradual() private view returns (GlobalGradual memory global, bool didUpdate) { uint256 lastFinishedTrancheIndex = getLastFinishedTrancheIndex(); global = _globalGradual; // update gradual until we reach last finished index while (global.lastUpdatedTrancheIndex < lastFinishedTrancheIndex) { // increment index before updating so we calculate based on finished index global.lastUpdatedTrancheIndex++; _updateGradualForTrancheIndex(global); didUpdate = true; } } /** * @notice update global gradual values for tranche `index` * @dev the update is done in-memory on `global` struct * * @param global global gradual struct */ function _updateGradualForTrancheIndex(GlobalGradual memory global) private view { // update unmatured voting power // every new tranche we add totalMaturingAmount to the _totalRawUnmaturedVotingPower global.totalRawUnmaturedVotingPower += global.totalMaturingAmount; // move newly matured voting power to matured // do only if contract is old enough so full power could be achieved if (global.lastUpdatedTrancheIndex >= FULL_POWER_TRANCHES_COUNT) { uint256 maturedIndex = global.lastUpdatedTrancheIndex - FULL_POWER_TRANCHES_COUNT + 1; uint48 newMaturedVotingPower = _getTranche(maturedIndex).amount; // if there is any new fully-matured voting power, update if (newMaturedVotingPower > 0) { // remove new fully matured voting power from non matured raw one uint56 newMaturedAsRawUnmatured = _getMaturedAsRawUnmaturedAmount(newMaturedVotingPower); global.totalRawUnmaturedVotingPower -= newMaturedAsRawUnmatured; // remove new fully-matured power from maturing amount global.totalMaturingAmount -= newMaturedVotingPower; // add new fully-matured voting power global.totalMaturedVotingPower += newMaturedVotingPower; } } } /* ---------- GRADUAL POWER: UPDATE USER FUNCTIONS ---------- */ /** * @notice update gradual user voting power * @dev also updates global gradual voting power * * Requirements: * * - the caller must be the gradual minter * * @param user user address to update */ function updateUserVotingPower(address user) external override onlyGradualMinter { _updateGradual(); _updateGradualUser(user); } /** * @notice update gradual user struct storage * * @param user user address to update */ function _updateGradualUser(address user) private { (UserGradual memory _userGradual, bool didUpdate) = _getUpdatedGradualUser(user); if (didUpdate) { _userGraduals[user] = _userGradual; emit UserGradualUpdated( user, _userGradual.lastUpdatedTrancheIndex, _userGradual.maturedVotingPower, _userGradual.maturingAmount, _userGradual.rawUnmaturedVotingPower ); } } /** * @notice returns updated user gradual struct * @dev the update is returned in-memory * The update is done in 3 steps: * 1. check if user ia alreas, update last updated undex * 2. update voting power for tranches that have fully-matured (if any) * 3. update voting power for tranches that are still maturing * * @param user updated for user address * @return _userGradual updated user gradual struct * @return didUpdate flag if user gradual has updated */ function _getUpdatedGradualUser(address user) private view returns (UserGradual memory, bool) { UserGradual memory _userGradual = _userGraduals[user]; uint16 lastFinishedTrancheIndex = getLastFinishedTrancheIndex(); // 1. if user already updated in this tranche index, skip if (_userGradual.lastUpdatedTrancheIndex == lastFinishedTrancheIndex) { return (_userGradual, false); } // update user if it has maturing power if (_hasTranches(_userGradual)) { // 2. update fully-matured tranches uint16 lastMaturedIndex = _getLastMaturedIndex(); if (lastMaturedIndex > 0) { UserTranche memory oldestTranche = _getUserTranche(user, _userGradual.oldestTranchePosition); // update all fully-matured user tranches while (_hasTranches(_userGradual) && oldestTranche.index <= lastMaturedIndex) { // mature _matureOldestUsersTranche(_userGradual, oldestTranche); // get new user oldest tranche oldestTranche = _getUserTranche(user, _userGradual.oldestTranchePosition); } } // 3. update still maturing tranches if (_isMaturing(_userGradual, lastFinishedTrancheIndex)) { // get number of passed indexes uint56 indexesPassed = lastFinishedTrancheIndex - _userGradual.lastUpdatedTrancheIndex; // add new user matured power _userGradual.rawUnmaturedVotingPower += _userGradual.maturingAmount * indexesPassed; // last synced index _userGradual.lastUpdatedTrancheIndex = lastFinishedTrancheIndex; } } // update user last updated tranche index _userGradual.lastUpdatedTrancheIndex = lastFinishedTrancheIndex; return (_userGradual, true); } /** * @notice mature users oldest tranche, and update oldest with next user tranche * @dev this is called only if we know `oldestTranche` is mature * Updates are done im-memory * * @param _userGradual user gradual struct to update * @param oldestTranche users oldest struct (fully matured one) */ function _matureOldestUsersTranche(UserGradual memory _userGradual, UserTranche memory oldestTranche) private pure { uint16 fullyMaturedFinishedIndex = _getFullyMaturedAtFinishedIndex(oldestTranche.index); uint48 newMaturedVotingPower = oldestTranche.amount; // add new matured voting power // calculate number of passed indexes between last update until fully matured index uint56 indexesPassed = fullyMaturedFinishedIndex - _userGradual.lastUpdatedTrancheIndex; _userGradual.rawUnmaturedVotingPower += _userGradual.maturingAmount * indexesPassed; // update new fully-matured voting power uint56 newMaturedAsRawUnmatured = _getMaturedAsRawUnmaturedAmount(newMaturedVotingPower); // update user gradual values in respect of new fully-matured amount // remove new fully matured voting power from non matured raw one _userGradual.rawUnmaturedVotingPower -= newMaturedAsRawUnmatured; // add new fully-matured voting power _userGradual.maturedVotingPower += newMaturedVotingPower; // remove new fully-matured power from maturing amount _userGradual.maturingAmount -= newMaturedVotingPower; // add next tranche as oldest _setNextOldestUserTranchePosition(_userGradual); // update last updated index until fully matured index _userGradual.lastUpdatedTrancheIndex = fullyMaturedFinishedIndex; } /** * @notice returns index at which the maturing will finish * @dev * e.g. if FULL_POWER_TRANCHES_COUNT=2 and passing index=1, * maturing will complete at the end of index 2. * This is the index we return, similar to last finished index. * * @param index index from which to derive fully matured finished index */ function _getFullyMaturedAtFinishedIndex(uint256 index) private pure returns (uint16) { return uint16(index + FULL_POWER_TRANCHES_COUNT - 1); } /** * @notice updates user oldest tranche position to next one in memory * @dev this is done after an oldest tranche position matures * If oldest tranch position is same as latest one, all user * tranches have matured. In this case we remove tranhe positions from the user * * @param _userGradual user gradual struct to update */ function _setNextOldestUserTranchePosition(UserGradual memory _userGradual) private pure { // if oldest tranche is same as latest, this was the last tranche and we remove it from the user if ( _userGradual.oldestTranchePosition.arrayIndex == _userGradual.latestTranchePosition.arrayIndex && _userGradual.oldestTranchePosition.position == _userGradual.latestTranchePosition.position ) { // reset user tranches as all of them matured _userGradual.oldestTranchePosition = UserTranchePosition(0, 0); } else { // set next user tranche as oldest _userGradual.oldestTranchePosition = _getNextUserTranchePosition(_userGradual.oldestTranchePosition); } } /* ---------- GRADUAL POWER: GLOBAL HELPER FUNCTIONS ---------- */ /** * @notice returns total gradual voting power from `global` * @dev the returned amount is untrimmed * * @param global global gradual struct * @return totalGradualVotingPower total gradual voting power (fully-matured + maturing) */ function _getTotalGradualVotingPower(GlobalGradual memory global) private pure returns (uint256) { return _untrim(global.totalMaturedVotingPower) + _getMaturingVotingPowerFromRaw(_untrim(global.totalRawUnmaturedVotingPower)); } /** * @notice returns global tranche storage struct * @dev we return struct, so we can manipulate the storage in other functions * * @param index tranche index * @return tranche tranche storage struct */ function _getTranche(uint256 index) private view returns (Tranche storage) { uint256 arrayindex = index / TRANCHES_PER_WORD; GlobalTranches storage globalTranches = indexedGlobalTranches[arrayindex]; uint256 globalTranchesPosition = index % TRANCHES_PER_WORD; if (globalTranchesPosition == 0) { return globalTranches.zero; } else if (globalTranchesPosition == 1) { return globalTranches.one; } else if (globalTranchesPosition == 2) { return globalTranches.two; } else if (globalTranchesPosition == 3) { return globalTranches.three; } else { return globalTranches.four; } } /* ---------- GRADUAL POWER: USER HELPER FUNCTIONS ---------- */ /** * @notice gets `user` `tranche` at position * * @param user user address to get tranche from * @param userTranchePosition position to get the `tranche` from * @return tranche `user` tranche */ function _getUserTranche(address user, UserTranchePosition memory userTranchePosition) private view returns (UserTranche memory tranche) { UserTranches storage _userTranches = userTranches[user][userTranchePosition.arrayIndex]; if (userTranchePosition.position == 0) { tranche = _userTranches.zero; } else if (userTranchePosition.position == 1) { tranche = _userTranches.one; } else if (userTranchePosition.position == 2) { tranche = _userTranches.two; } else { tranche = _userTranches.three; } } /** * @notice return last matured tranche index * * @return lastMaturedIndex last matured tranche index */ function _getLastMaturedIndex() private view returns (uint16 lastMaturedIndex) { uint256 currentTrancheIndex = getCurrentTrancheIndex(); if (currentTrancheIndex > FULL_POWER_TRANCHES_COUNT) { unchecked { lastMaturedIndex = uint16(currentTrancheIndex - FULL_POWER_TRANCHES_COUNT); } } } /** * @notice returns the user gradual voting power (fully-matured and maturing) * @dev the returned amount is untrimmed * * @param _userGradual user gradual struct * @return userGradualVotingPower user gradual voting power (fully-matured + maturing) */ function _getUserGradualVotingPower(UserGradual memory _userGradual) private pure returns (uint256) { return _untrim(_userGradual.maturedVotingPower) + _getMaturingVotingPowerFromRaw(_untrim(_userGradual.rawUnmaturedVotingPower)); } /** * @notice returns next user tranche position, based on current one * * @param currentTranchePosition current user tranche position * @return nextTranchePosition next tranche position of `currentTranchePosition` */ function _getNextUserTranchePosition(UserTranchePosition memory currentTranchePosition) private pure returns (UserTranchePosition memory nextTranchePosition) { if (currentTranchePosition.arrayIndex == 0) { nextTranchePosition.arrayIndex = 1; } else { if (currentTranchePosition.position < 3) { nextTranchePosition.arrayIndex = currentTranchePosition.arrayIndex; nextTranchePosition.position = currentTranchePosition.position + 1; } else { nextTranchePosition.arrayIndex = currentTranchePosition.arrayIndex + 1; } } } /** * @notice check if user requires maturing * * @param _userGradual user gradual struct to update * @param lastFinishedTrancheIndex index of last finished tranche index * @return needsMaturing true if user needs maturing, else false */ function _isMaturing(UserGradual memory _userGradual, uint256 lastFinishedTrancheIndex) private pure returns (bool) { return _userGradual.lastUpdatedTrancheIndex < lastFinishedTrancheIndex && _hasTranches(_userGradual); } /** * @notice check if user gradual has any non-matured tranches * * @param _userGradual user gradual struct * @return hasTranches true if user has non-matured tranches */ function _hasTranches(UserGradual memory _userGradual) private pure returns (bool hasTranches) { if (_userGradual.oldestTranchePosition.arrayIndex > 0) { hasTranches = true; } } /* ---------- GRADUAL POWER: HELPER FUNCTIONS ---------- */ /** * @notice return trimmed amount * @dev `amount` is trimmed by `TRIM_SIZE`. * This is done so the amount can be represented in 48bits. * This still gives us enough accuracy so the core logic is not affected. * * @param amount amount to trim * @return trimmedAmount amount divided by `TRIM_SIZE` */ function _trim(uint256 amount) private pure returns (uint48) { return uint48(amount / TRIM_SIZE); } /** * @notice return trimmed amount rounding up if any dust left * * @param amount amount to trim * @return trimmedAmount amount divided by `TRIM_SIZE`, rounded up */ function _trimRoundUp(uint256 amount) private pure returns (uint48 trimmedAmount) { trimmedAmount = _trim(amount); if (_untrim(trimmedAmount) < amount) { unchecked { trimmedAmount++; } } } /** * @notice untrim `trimmedAmount` in respect to `TRIM_SIZE` * * @param trimmedAmount amount previously trimemd * @return untrimmedAmount untrimmed amount */ function _untrim(uint256 trimmedAmount) private pure returns (uint256) { unchecked { return trimmedAmount * TRIM_SIZE; } } /** * @notice calculates voting power from raw unmatured * * @param rawMaturingVotingPower raw maturing voting power amount * @return maturingVotingPower actual maturing power amount */ function _getMaturingVotingPowerFromRaw(uint256 rawMaturingVotingPower) private pure returns (uint256) { return rawMaturingVotingPower / FULL_POWER_TRANCHES_COUNT; } /** * @notice Returns amount represented in raw unmatured value * @dev used to substract fully-matured amount from raw unmatured, when amount matures * * @param amount matured amount * @return asRawUnmatured `amount` multiplied by `FULL_POWER_TRANCHES_COUNT` (raw unmatured amount) */ function _getMaturedAsRawUnmaturedAmount(uint48 amount) private pure returns (uint56) { unchecked { return uint56(amount * FULL_POWER_TRANCHES_COUNT); } } /* ========== OWNER FUNCTIONS ========== */ /** * @notice Sets or resets the instant minter address * * Requirements: * * - the caller must be the owner of the contract * - the minter must not be the zero address * * @param _minter address to set * @param _set true to set, false to reset */ function setMinter(address _minter, bool _set) external onlyOwner { require(_minter != address(0), "voSPOOL::setMinter: minter cannot be the zero address"); minters[_minter] = _set; emit MinterSet(_minter, _set); } /** * @notice Sets or resets the gradual minter address * * Requirements: * * - the caller must be the owner of the contract * - the minter must not be the zero address * * @param _gradualMinter address to set * @param _set true to set, false to reset */ function setGradualMinter(address _gradualMinter, bool _set) external onlyOwner { require(_gradualMinter != address(0), "voSPOOL::setGradualMinter: gradual minter cannot be the zero address"); gradualMinters[_gradualMinter] = _set; emit GradualMinterSet(_gradualMinter, _set); } /* ========== RESTRICTION FUNCTIONS ========== */ /** * @notice Ensures the caller is the instant minter */ function _onlyMinter() private view { require(minters[msg.sender], "voSPOOL::_onlyMinter: Insufficient Privileges"); } /** * @notice Ensures the caller is the gradual minter */ function _onlyGradualMinter() private view { require(gradualMinters[msg.sender], "voSPOOL::_onlyGradualMinter: Insufficient Privileges"); } /* ========== MODIFIERS ========== */ /** * @notice Throws if the caller is not the instant miter */ modifier onlyMinter() { _onlyMinter(); _; } /** * @notice Throws if the caller is not the gradual minter */ modifier onlyGradualMinter() { _onlyGradualMinter(); _; } /** * @notice Update global gradual values */ modifier updateGradual() { _updateGradual(); _; } /** * @notice Update user gradual values */ modifier updateGradualUser(address user) { _updateGradualUser(user); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./interfaces/ISpoolOwner.sol"; abstract contract SpoolOwnable { ISpoolOwner internal immutable spoolOwner; constructor(ISpoolOwner _spoolOwner) { require( address(_spoolOwner) != address(0), "SpoolOwnable::constructor: Spool owner contract address cannot be 0" ); spoolOwner = _spoolOwner; } function isSpoolOwner() internal view returns(bool) { return spoolOwner.isSpoolOwner(msg.sender); } function _onlyOwner() internal view { require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner"); } modifier onlyOwner() { _onlyOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface ISpoolOwner { function isSpoolOwner(address user) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; /* ========== STRUCTS ========== */ /** * @notice global gradual struct * @member totalMaturedVotingPower total fully-matured voting power amount * @member totalMaturingAmount total maturing amount (amount of power that is accumulating every week for 1/156 of the amount) * @member totalRawUnmaturedVotingPower total raw voting power still maturing every tranche (totalRawUnmaturedVotingPower/156 is its voting power) * @member lastUpdatedTrancheIndex last (finished) tranche index global gradual has updated */ struct GlobalGradual { uint48 totalMaturedVotingPower; uint48 totalMaturingAmount; uint56 totalRawUnmaturedVotingPower; uint16 lastUpdatedTrancheIndex; } /** * @notice user tranche position struct, pointing at user tranche * @dev points at `userTranches` mapping * @member arrayIndex points at `userTranches` * @member position points at UserTranches position from zero to three (zero, one, two, or three) */ struct UserTranchePosition { uint16 arrayIndex; uint8 position; } /** * @notice user gradual struct, similar to global gradual holds user gragual voting power values * @dev points at `userTranches` mapping * @member maturedVotingPower users fully-matured voting power amount * @member maturingAmount users maturing amount * @member rawUnmaturedVotingPower users raw voting power still maturing every tranche * @member oldestTranchePosition UserTranchePosition pointing at the oldest unmatured UserTranche * @member latestTranchePosition UserTranchePosition pointing at the latest unmatured UserTranche * @member lastUpdatedTrancheIndex last (finished) tranche index user gradual has updated */ struct UserGradual { uint48 maturedVotingPower; // matured voting amount, power accumulated and older than FULL_POWER_TIME, not accumulating anymore uint48 maturingAmount; // total maturing amount (also maximum matured) uint56 rawUnmaturedVotingPower; // current user raw unmatured voting power (increases every new tranche), actual unmatured voting power can be calculated as unmaturedVotingPower / FULL_POWER_TRANCHES_COUNT UserTranchePosition oldestTranchePosition; // if arrayIndex is 0, user has no tranches (even if `latestTranchePosition` is not empty) UserTranchePosition latestTranchePosition; // can only increment, in case of tranche removal, next time user gradually mints we point at tranche at next position uint16 lastUpdatedTrancheIndex; } /** * @title Spool DAO Voting Token interface */ interface IVoSPOOL { /* ========== FUNCTIONS ========== */ function mint(address, uint256) external; function burn(address, uint256) external; function mintGradual(address, uint256) external; function burnGradual( address, uint256, bool ) external; function updateVotingPower() external; function updateUserVotingPower(address user) external; function getTotalGradualVotingPower() external returns (uint256); function getUserGradualVotingPower(address user) external returns (uint256); function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory); function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory); function getCurrentTrancheIndex() external view returns (uint16); function getLastFinishedTrancheIndex() external view returns (uint16); /* ========== EVENTS ========== */ event Minted(address indexed recipient, uint256 amount); event Burned(address indexed source, uint256 amount); event GradualMinted(address indexed recipient, uint256 amount); event GradualBurned(address indexed source, uint256 amount, bool burnAll); event GlobalGradualUpdated( uint16 indexed lastUpdatedTrancheIndex, uint48 totalMaturedVotingPower, uint48 totalMaturingAmount, uint56 totalRawUnmaturedVotingPower ); event UserGradualUpdated( address indexed user, uint16 indexed lastUpdatedTrancheIndex, uint48 maturedVotingPower, uint48 maturingAmount, uint56 rawUnmaturedVotingPower ); event MinterSet(address indexed minter, bool set); event GradualMinterSet(address indexed minter, bool set); }
* @notice returns total gradual voting power from `global` @dev the returned amount is untrimmed @param global global gradual struct @return totalGradualVotingPower total gradual voting power (fully-matured + maturing)/
function _getTotalGradualVotingPower(GlobalGradual memory global) private pure returns (uint256) { return _untrim(global.totalMaturedVotingPower) + _getMaturingVotingPowerFromRaw(_untrim(global.totalRawUnmaturedVotingPower)); }
233,238
[ 1, 6154, 2078, 6058, 1462, 331, 17128, 7212, 628, 1375, 6347, 68, 225, 326, 2106, 3844, 353, 640, 5290, 2937, 225, 2552, 2552, 6058, 1462, 1958, 327, 2078, 30420, 1462, 58, 17128, 13788, 2078, 6058, 1462, 331, 17128, 7212, 261, 4095, 17, 81, 1231, 72, 397, 4834, 4017, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 588, 5269, 30420, 1462, 58, 17128, 13788, 12, 5160, 30420, 1462, 3778, 2552, 13, 3238, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 2463, 203, 1082, 202, 67, 318, 5290, 12, 6347, 18, 4963, 49, 1231, 72, 58, 17128, 13788, 13, 397, 203, 1082, 202, 67, 588, 15947, 4017, 58, 17128, 13788, 1265, 4809, 24899, 318, 5290, 12, 6347, 18, 4963, 4809, 984, 81, 1231, 72, 58, 17128, 13788, 10019, 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 ]
pragma solidity ^0.8.3; /* * \title Hakutaku token * \brief Token that every X hours rewards a randomly selected holder (that held for long enough) * with the total amount accumulated in a pool from transaction fees * \version 1.0b experimental * \author unknown */ import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; contract HTT is ERC20, Ownable { address prize_pool; //!< prize draw pool address uint prize_pool_fee; //!< percent fee on every transaction that goes towards prize pool (1-10% limit) uint prize_frequency; //!< how often does the prize draw happen (1h - 1d limit) uint hold_balance_limit; //!< amount to hold to be eligible for a prize draw (1-1M token limit) uint hold_time_limit; //!< must hold at least this time (2-25 hr limit) struct Holder { address addr; uint time; // timestamp when accumulated enough HTT } Holder[] holders; //!< holders (will become diamond hands once time passes) struct Diamond { address addr; uint value; // value with which became a diamond hands holder } Diamond[] diamonds; //!< eligible holders for the reward (diamond hands) mapping(address => uint) holder_indexes; //!< mapping of address to indexes in holders array mapping(address => uint) diamond_indexes; //!< mapping of address to indexes in diamonds array uint prize_last_time; //!< last time the prize draw happened uint prize_last_amount; //!< last amount given to rewardee uint totalam; //!< total amount of tokens diamond hands accumulated bool buy_limit; //!< protection from whales (removed shortly after the launch) constructor( address _prize_pool, uint _prize_pool_fee, uint _prize_frequency, uint _hold_balance_limit, uint _hold_time_limit, bool _buy_limit) Ownable() ERC20('Hakutaku Token', 'HAKU') { _mint(msg.sender, 1000000000 * 10 ** 18); _addHolder(msg.sender); // fill index 0 _addDiamond(msg.sender, _hold_balance_limit); // fill index 0 totalam = 0; // init totalam prize_pool = _prize_pool; // hardcoded prize pool (this account will not be able to trade tokens!) setPrizePoolFee(_prize_pool_fee); setHoldTimeLimit(_hold_time_limit); setPrizeFrequency(_prize_frequency); setHoldBalanceLimit(_hold_balance_limit); prize_last_time = block.timestamp; // init prize timestamp prize_last_amount = 0; buy_limit = _buy_limit; } /*! * \title Override transfer function * \brief Takes prize fee from every transaction * Initiates reward prize draw */ function _transfer(address from, address to, uint256 value) override internal { // block prize pool from dumping tokens require(from != prize_pool, "prize pool cannot trade tokens"); require(to != prize_pool, "prize pool cannot trade tokens"); // put fee into the prize pool if(from != owner() && to != owner()) { uint256 prize_fee = calcFee(value); value -= prize_fee; // take fee out if(buy_limit) { require(value <= hold_balance_limit, "buy/sell limit"); require(balanceOf(to) + value <= hold_balance_limit, "hold limit"); } super._transfer(from, prize_pool, prize_fee); } super._transfer(from, to, value); // are there pending holders waiting to become diamond hands? if(holders.length > 1) { uint i = holders.length-1; uint steps = 0; // process max 10 at a time to save gas while(steps < 10 && i > 0) { if(holder_indexes[holders[i].addr] > 0 && diamond_indexes[holders[i].addr] == 0 && holders[i].time > 0 && (block.timestamp - holders[i].time) >= hold_time_limit) { _addDiamond(holders[i].addr, balanceOf(holders[i].addr)); // add to diamond hands _removeHolder(holders[i].addr); // delete from pending } steps++; i--; } } // do we need to trigger a reward? if(block.timestamp > prize_last_time && (block.timestamp - prize_last_time) >= prize_frequency && balanceOf(prize_pool) > 0) { prize_last_time = block.timestamp; // update last time a prize was given // prize given only if there are diamond hands if(diamonds.length > 1) { // calc total amount for mid, 1/4 and 3/4 holder uint indmid = uint(diamonds.length) / uint(2); uint indlq = indmid / uint(2); uint totalamex = diamonds[indmid].value + diamonds[indlq].value + diamonds[indlq+indmid].value; // choose a rewardee from diamond hands holders uint rewardee_ind = 1 + getHakutakuChoice(diamonds.length-1, totalamex); // if we get 0, it's 1 prize_last_amount = balanceOf(prize_pool); // give everything from the prize pool to the rewardee super._transfer(prize_pool, diamonds[rewardee_ind].addr, prize_last_amount); } } // if accumulated enough and not in holders yet -- add // note1: owner is a permanent holder (but will never take part in prize draws!) // note2: prize_pool is not in holders and never will be // note3: owner and prize pool do not get added or removed to these lists after constructor uint bto = balanceOf(to); uint bfrom = balanceOf(from); if(bto >= hold_balance_limit && holder_indexes[to] == 0 && diamond_indexes[to] == 0 && to != owner() && to != prize_pool) { _addHolder(to); } if(bfrom >= hold_balance_limit && holder_indexes[from] == 0 && diamond_indexes[from] == 0 && from != owner() && from != prize_pool) { _addHolder(from); } // if below hold limit (he sold? d0mp him!) if(bfrom < hold_balance_limit && from != owner() && from != prize_pool) { if(holder_indexes[from] > 0) { _removeHolder(from); } if(diamond_indexes[from] > 0) { _removeDiamond(from); } } if(bto < hold_balance_limit && to != owner() && to != prize_pool) { if(holder_indexes[to] > 0) { _removeHolder(to); } if(diamond_indexes[to] > 0) { _removeDiamond(to); } } } /*! * \title Hakutaku makes a choice of the rewardee * \brief He decides based on what holders did. It is completely decentralised. * Warning: the choice is pseudo-random, not strictly random, this code is experimental * Note, however, that the hypothetical effort to turn this choice into personal benefit via an exploit * is expected to be larger than the benefit because of the holding time limit, holding amount limit and * randomness introduced by holder actions. Moreover, the frequency of the prize draw in comparison with * the holding time limit and holding balance limit makes the cost of manipulation too high. * With that being said, we don't make any claims, it is experimental, always do your own research. * \return index of the rewardee */ function getHakutakuChoice(uint num, uint totalamex) internal view returns(uint) { return uint(keccak256(abi.encodePacked(totalam, totalamex, prize_last_amount))) % num; } /*! * \title Calculate prize fee for a transaction value * \return fee in tokens */ function calcFee(uint256 value) public view returns (uint256) { return (value / 100) * prize_pool_fee; } function _addHolder(address holder) internal { holders.push(Holder(holder, block.timestamp)); holder_indexes[holder] = holders.length - 1; } function _removeHolder(address holder) internal { uint ind = holder_indexes[holder]; if(ind < holders.length-1) { holders[ind] = holders[holders.length-1]; // replace current index with last holder holder_indexes[holders[ind].addr] = ind; // update last holder's index to new one } holders.pop(); // pop last item of the holders delete holder_indexes[holder]; // clear the holder who sold } function _addDiamond(address diamond, uint value) internal { diamonds.push(Diamond(diamond, value)); diamond_indexes[diamond] = diamonds.length - 1; totalam += value; } function _removeDiamond(address diamond) internal { uint ind = diamond_indexes[diamond]; totalam -= diamonds[ind].value; // his value is out of the totalam if(ind < diamonds.length-1) { diamonds[ind] = diamonds[diamonds.length-1]; // replace current index with last diamond diamond_indexes[diamonds[ind].addr] = ind; // update last diamond's index to new one } diamonds.pop(); // pop last item of the holders delete diamond_indexes[diamond]; // clear the diamond who sold } function getPrizeLastTime() external view returns (uint) { return prize_last_time; } function getPrizePoolFee() external view returns (uint) { return prize_pool_fee; } function getPrizeFrequency() external view returns (uint) { return prize_frequency; } function getHoldBalanceLimit() external view returns (uint) { return hold_balance_limit; } function getHoldTimeLimit() external view returns (uint) { return hold_time_limit; } function getHoldersCount() external view returns(uint) { return holders.length; } function getDiamondsCount() external view returns(uint) { return diamonds.length; } function setPrizeFrequency(uint _prize_frequency) public onlyOwner { require(_prize_frequency >= 1800 && _prize_frequency <= 86400, "frequency of the reward must be between 30m and 1d"); require(hold_time_limit >= 3600 + _prize_frequency, "houd hour limit must be at least 1 hour longer than reward frequency"); prize_frequency = _prize_frequency; } function setPrizePoolFee(uint _prize_pool_fee) public onlyOwner { require(_prize_pool_fee >= 1 && _prize_pool_fee <= 10, "prize pool fee must be 1-10%"); prize_pool_fee = _prize_pool_fee; } function setHoldBalanceLimit(uint _hold_balance_limit) public onlyOwner { require(_hold_balance_limit >= 1 * 10 ** 18 && _hold_balance_limit <= 10000000 * 10 ** 18, "balance limit must be between 1 and 10M"); hold_balance_limit = _hold_balance_limit; } function setHoldTimeLimit(uint _hold_time_limit) public onlyOwner { require(_hold_time_limit >= 7200 && _hold_time_limit <= 90000, "hold time limit has to be between 2 and 25"); require(_hold_time_limit >= 3600 + prize_frequency, "hold time limit must be at least 1 hour longer than reward frequency"); hold_time_limit = _hold_time_limit; } function removeBuyLimit() external onlyOwner { buy_limit = false; // can be done only once and can't be reverted! } }
update last holder's index to new one
holder_indexes[holders[ind].addr] = ind;
6,342,818
[ 1, 2725, 1142, 10438, 1807, 770, 358, 394, 1245, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1082, 202, 4505, 67, 11265, 63, 9000, 63, 728, 8009, 4793, 65, 273, 1547, 31, 1875, 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 ]
pragma solidity ^0.4.8; contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender == owner) _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) owner = newOwner; } } contract TokenSpender { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract PullPayment { mapping(address => uint) public payments; event RefundETH(address to, uint value); // store sent amount as credit to be pulled, called by payer function asyncSend(address dest, uint amount) internal { payments[dest] += amount; } // withdraw accumulated balance, called by payee function withdrawPayments() { address payee = msg.sender; uint payment = payments[payee]; if (payment == 0) { throw; } if (this.balance < payment) { throw; } payments[payee] = 0; if (!payee.send(payment)) { throw; } RefundETH(payee,payment); } } contract Pausable is Ownable { bool public stopped; modifier stopInEmergency { if (stopped) { throw; } _; } modifier onlyInEmergency { if (!stopped) { throw; } _; } // called by the owner on emergency, triggers stopped state function emergencyStop() external onlyOwner { stopped = true; } // called by the owner on end of emergency, returns to normal state function release() external onlyOwner onlyInEmergency { stopped = false; } } contract RLC is ERC20, SafeMath, Ownable { /* Public variables of the token */ string public name; //fancy name string public symbol; uint8 public decimals; //How many decimals to show. string public version = 'v0.1'; uint public initialSupply; uint public totalSupply; bool public locked; //uint public unlockBlock; mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; // lock transfer during the ICO modifier onlyUnlocked() { if (msg.sender != owner && locked) throw; _; } /* * The RLC Token created with the time at which the crowdsale end */ function RLC() { // lock the transfer function during the crowdsale locked = true; //unlockBlock= now + 45 days; // (testnet) - for mainnet put the block number initialSupply = 87000000000000000; totalSupply = initialSupply; balances[msg.sender] = initialSupply;// Give the creator all initial tokens name = 'iEx.ec Network Token'; // Set the name for display purposes symbol = 'RLC'; // Set the symbol for display purposes decimals = 9; // Amount of decimals for display purposes } function unlock() onlyOwner { locked = false; } function burn(uint256 _value) returns (bool){ balances[msg.sender] = safeSub(balances[msg.sender], _value) ; totalSupply = safeSub(totalSupply, _value); Transfer(msg.sender, 0x0, _value); return true; } function transfer(address _to, uint _value) onlyUnlocked returns (bool) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) onlyUnlocked returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* Approve and then comunicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData){ TokenSpender spender = TokenSpender(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); } } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract Crowdsale is SafeMath, PullPayment, Pausable { struct Backer { uint weiReceived; // Amount of ETH given string btc_address; //store the btc address for full traceability uint satoshiReceived; // Amount of BTC given uint rlcSent; } RLC public rlc; // RLC contract reference address public owner; // Contract owner (iEx.ec team) address public multisigETH; // Multisig contract that will receive the ETH address public BTCproxy; // address of the BTC Proxy uint public RLCPerETH; // Number of RLC per ETH uint public RLCPerSATOSHI; // Number of RLC per SATOSHI uint public ETHReceived; // Number of ETH received uint public BTCReceived; // Number of BTC received uint public RLCSentToETH; // Number of RLC sent to ETH contributors uint public RLCSentToBTC; // Number of RLC sent to BTC contributors uint public startBlock; // Crowdsale start block uint public endBlock; // Crowdsale end block uint public minCap; // Minimum number of RLC to sell uint public maxCap; // Maximum number of RLC to sell bool public maxCapReached; // Max cap has been reached uint public minInvestETH; // Minimum amount to invest uint public minInvestBTC; // Minimum amount to invest bool public crowdsaleClosed;// Is crowdsale still on going address public bounty; // address at which the bounty RLC will be sent address public reserve; // address at which the contingency reserve will be sent address public team; // address at which the team RLC will be sent uint public rlc_bounty; // amount of bounties RLC uint public rlc_reserve; // amount of the contingency reserve uint public rlc_team; // amount of the team RLC mapping(address => Backer) public backers; //backersETH indexed by their ETH address modifier onlyBy(address a){ if (msg.sender != a) throw; _; } modifier minCapNotReached() { if ((now<endBlock) || RLCSentToETH + RLCSentToBTC >= minCap ) throw; _; } modifier respectTimeFrame() { if ((now < startBlock) || (now > endBlock )) throw; _; } /* * Event */ event ReceivedETH(address addr, uint value); event ReceivedBTC(address addr, string from, uint value, string txid); event RefundBTC(string to, uint value); event Logs(address indexed from, uint amount, string value); /* * Constructor */ //function Crowdsale() { function Crowdsale() { owner = msg.sender; BTCproxy = 0x75c6cceb1a33f177369053f8a0e840de96b4ed0e; rlc = RLC(0x607f4c5bb672230e8672085532f7e901544a7375); multisigETH = 0xAe307e3871E5A321c0559FBf0233A38c937B826A; team = 0xd65380D773208a6Aa49472Bf55186b855B393298; reserve = 0x24F6b37770C6067D05ACc2aD2C42d1Bafde95d48; bounty = 0x8226a24dA0870Fb8A128E4Fc15228a9c4a5baC29; RLCSentToETH = 0; RLCSentToBTC = 0; minInvestETH = 1 ether; minInvestBTC = 5000000; // approx 50 USD or 0.05000000 BTC startBlock = 0 ; // should wait for the call of the function start endBlock = 0; // should wait for the call of the function start RLCPerETH = 200000000000; // will be update every 10min based on the kraken ETHBTC RLCPerSATOSHI = 50000; // 5000 RLC par BTC == 50,000 RLC per satoshi minCap=12000000000000000; maxCap=60000000000000000; rlc_bounty=1700000000000000; // max 6000000 RLC rlc_reserve=1700000000000000; // max 6000000 RLC rlc_team=12000000000000000; } /* * The fallback function corresponds to a donation in ETH */ function() payable { if (now > endBlock) throw; receiveETH(msg.sender); } /* * To call to start the crowdsale */ function start() onlyBy(owner) { startBlock = now ; endBlock = now + 30 days; } /* * Receives a donation in ETH */ function receiveETH(address beneficiary) internal stopInEmergency respectTimeFrame { if (msg.value < minInvestETH) throw; //don't accept funding under a predefined threshold uint rlcToSend = bonus(safeMul(msg.value,RLCPerETH)/(1 ether)); //compute the number of RLC to send if (safeAdd(rlcToSend, safeAdd(RLCSentToETH, RLCSentToBTC)) > maxCap) throw; Backer backer = backers[beneficiary]; if (!rlc.transfer(beneficiary, rlcToSend)) throw; // Do the RLC transfer right now backer.rlcSent = safeAdd(backer.rlcSent, rlcToSend); backer.weiReceived = safeAdd(backer.weiReceived, msg.value); // Update the total wei collected during the crowdfunding for this backer ETHReceived = safeAdd(ETHReceived, msg.value); // Update the total wei collected during the crowdfunding RLCSentToETH = safeAdd(RLCSentToETH, rlcToSend); emitRLC(rlcToSend); // compute the variable part ReceivedETH(beneficiary,ETHReceived); // send the corresponding contribution event } /* * receives a donation in BTC */ function receiveBTC(address beneficiary, string btc_address, uint value, string txid) stopInEmergency respectTimeFrame onlyBy(BTCproxy) returns (bool res){ if (value < minInvestBTC) throw; // this verif is also made on the btcproxy uint rlcToSend = bonus(safeMul(value,RLCPerSATOSHI)); //compute the number of RLC to send if (safeAdd(rlcToSend, safeAdd(RLCSentToETH, RLCSentToBTC)) > maxCap) { // check if we are not reaching the maxCap by accepting this donation RefundBTC(btc_address , value); return false; } Backer backer = backers[beneficiary]; if (!rlc.transfer(beneficiary, rlcToSend)) throw; // Do the transfer right now backer.rlcSent = safeAdd(backer.rlcSent , rlcToSend); backer.btc_address = btc_address; backer.satoshiReceived = safeAdd(backer.satoshiReceived, value); BTCReceived = safeAdd(BTCReceived, value); // Update the total satoshi collected during the crowdfunding for this backer RLCSentToBTC = safeAdd(RLCSentToBTC, rlcToSend); // Update the total satoshi collected during the crowdfunding emitRLC(rlcToSend); ReceivedBTC(beneficiary, btc_address, BTCReceived, txid); return true; } /* *Compute the variable part */ function emitRLC(uint amount) internal { rlc_bounty = safeAdd(rlc_bounty, amount/10); rlc_team = safeAdd(rlc_team, amount/20); rlc_reserve = safeAdd(rlc_reserve, amount/10); Logs(msg.sender ,amount, "emitRLC"); } /* *Compute the RLC bonus according to the investment period */ function bonus(uint amount) internal constant returns (uint) { if (now < safeAdd(startBlock, 10 days)) return (safeAdd(amount, amount/5)); // bonus 20% if (now < safeAdd(startBlock, 20 days)) return (safeAdd(amount, amount/10)); // bonus 10% return amount; } /* * When mincap is not reach backer can call the approveAndCall function of the RLC token contract * with this crowdsale contract on parameter with all the RLC they get in order to be refund */ function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) minCapNotReached public { if (msg.sender != address(rlc)) throw; if (_extraData.length != 0) throw; // no extradata needed if (_value != backers[_from].rlcSent) throw; // compare value from backer balance if (!rlc.transferFrom(_from, address(this), _value)) throw ; // get the token back to the crowdsale contract if (!rlc.burn(_value)) throw ; // token sent for refund are burnt uint ETHToSend = backers[_from].weiReceived; backers[_from].weiReceived=0; uint BTCToSend = backers[_from].satoshiReceived; backers[_from].satoshiReceived = 0; if (ETHToSend > 0) { asyncSend(_from,ETHToSend); // pull payment to get refund in ETH } if (BTCToSend > 0) RefundBTC(backers[_from].btc_address ,BTCToSend); // event message to manually refund BTC } /* * Update the rate RLC per ETH, computed externally by using the ETHBTC index on kraken every 10min */ function setRLCPerETH(uint rate) onlyBy(BTCproxy) { RLCPerETH=rate; } /* * Finalize the crowdsale, should be called after the refund period */ function finalize() onlyBy(owner) { // check if (RLCSentToETH + RLCSentToBTC < maxCap - 5000000000000 && now < endBlock) throw; // cannot finalise before 30 day until maxcap is reached minus 1BTC if (RLCSentToETH + RLCSentToBTC < minCap && now < endBlock + 15 days) throw ; // if mincap is not reached donors have 15days to get refund before we can finalise if (!multisigETH.send(this.balance)) throw; // moves the remaining ETH to the multisig address if (rlc_reserve > 6000000000000000){ // moves RLC to the team, reserve and bounty address if(!rlc.transfer(reserve,6000000000000000)) throw; // max cap 6000000RLC rlc_reserve = 6000000000000000; } else { if(!rlc.transfer(reserve,rlc_reserve)) throw; } if (rlc_bounty > 6000000000000000){ if(!rlc.transfer(bounty,6000000000000000)) throw; // max cap 6000000RLC rlc_bounty = 6000000000000000; } else { if(!rlc.transfer(bounty,rlc_bounty)) throw; } if (!rlc.transfer(team,rlc_team)) throw; uint RLCEmitted = rlc_reserve + rlc_bounty + rlc_team + RLCSentToBTC + RLCSentToETH; if (RLCEmitted < rlc.totalSupply()) // burn the rest of RLC rlc.burn(rlc.totalSupply() - RLCEmitted); rlc.unlock(); crowdsaleClosed = true; } /* * Failsafe drain */ function drain() onlyBy(owner) { if (!owner.send(this.balance)) throw; } }
Amount of BTC given
uint satoshiReceived;
13,074,967
[ 1, 6275, 434, 605, 15988, 864, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 202, 11890, 5942, 538, 12266, 8872, 31, 202, 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.5.17; import "./LiquidityMiningStorage.sol"; contract LiquidityMiningStorageV1 is LiquidityMiningStorage { /// @dev Careful when adding new states as there is a < comparison being used in the modifiers enum MigrationGracePeriodStates { None, Started, // users can withdraw funds and rewards but not deposit Finished // users can't operate with the contract } /// @dev Represents migration grace period state MigrationGracePeriodStates public migrationGracePeriodState; /// @dev liquidity mining V2 contract address address public liquidityMiningV2; }
@dev liquidity mining V2 contract address
address public liquidityMiningV2;
5,493,355
[ 1, 549, 372, 24237, 1131, 310, 776, 22, 6835, 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, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 2867, 1071, 4501, 372, 24237, 2930, 310, 58, 22, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xF9ADf8038617B076169eC55594c46DCc1b3311F2/sources/contracts/voting.sol
Give `voter` the right to vote on this ballot. May only be called by `chairperson`. If the first argument of `require` evaluates to `false`, execution terminates and all changes to the state and to Ether balances are reverted. This used to consume all gas in old EVM versions, but not anymore. It is often a good idea to use `require` to check if functions are called correctly. As a second argument, you can also provide an explanation about what went wrong.
function giveRightToVote(address voter) external { require( msg.sender == chairperson, "Only chairperson can give right to vote." ); require( !voters[voter].voted, "The voter already voted." ); require(voters[voter].weight == 0); voters[voter].weight = 1; }
8,101,298
[ 1, 43, 688, 1375, 90, 20005, 68, 326, 2145, 358, 12501, 603, 333, 26503, 352, 18, 16734, 1338, 506, 2566, 635, 1375, 343, 1826, 12479, 8338, 971, 326, 1122, 1237, 434, 1375, 6528, 68, 20996, 358, 1375, 5743, 9191, 4588, 30559, 471, 777, 3478, 358, 326, 919, 471, 358, 512, 1136, 324, 26488, 854, 15226, 329, 18, 1220, 1399, 358, 7865, 777, 16189, 316, 1592, 512, 7397, 5244, 16, 1496, 486, 16828, 18, 2597, 353, 16337, 279, 7494, 21463, 358, 999, 1375, 6528, 68, 358, 866, 309, 4186, 854, 2566, 8783, 18, 2970, 279, 2205, 1237, 16, 1846, 848, 2546, 5615, 392, 21285, 2973, 4121, 16343, 7194, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 8492, 4726, 774, 19338, 12, 2867, 331, 20005, 13, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 462, 1826, 12479, 16, 203, 5411, 315, 3386, 462, 1826, 12479, 848, 8492, 2145, 358, 12501, 1199, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 401, 90, 352, 414, 63, 90, 20005, 8009, 90, 16474, 16, 203, 5411, 315, 1986, 331, 20005, 1818, 331, 16474, 1199, 203, 3639, 11272, 203, 3639, 2583, 12, 90, 352, 414, 63, 90, 20005, 8009, 4865, 422, 374, 1769, 203, 3639, 331, 352, 414, 63, 90, 20005, 8009, 4865, 273, 404, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title HighStreet Nft Pool * */ contract HighStreetNftPool is ReentrancyGuard, ERC721Holder { /** * @dev Deposit is a key data structure used in staking, * it represents a unit of reward with its amount and time interval */ struct Deposit { // @dev reward amount uint256 rewardAmount; // @dev locking period - from uint64 lockedFrom; // @dev locking period - until uint64 lockedUntil; } /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked NFT amount uint256 tokenAmount; // @dev Total reward amount uint256 rewardAmount; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev An array of holder's nft uint16[] list; // @dev An array of holder's rewards Deposit[] deposits; } /// @dev Link to HIGH STREET ERC20 Token instance address public immutable HIGH; /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to the pool token instance, here is the Duck NFT address public immutable poolToken; /// @dev Block number of the last yield distribution event uint256 public lastYieldDistribution; /// @dev Used to calculate yield rewards uint256 public yieldRewardsPerToken; /// @dev Used to calculate yield rewards, tracking the token amount in the pool uint256 public usersLockingAmount; /// @dev HIGH/block determines yield farming reward uint256 public highPerBlock; /** * @dev End block is the last block when yield farming stops */ uint256 public endBlock; /** * @dev Rewards per token are stored multiplied by 1e24, as integers */ uint256 internal constant REWARD_PER_TOKEN_MULTIPLIER = 1e24; /** * @dev Define the size of each batch, see getDepositsBatch() */ uint256 public constant DEPOSIT_BATCH_SIZE = 20; /** * @dev Define the size of each batch, see getNftsBatch() */ uint256 public constant NFT_BATCH_SIZE = 100; /** * @dev Handle the nft id equal to zero */ uint16 internal constant UINT_16_MAX = type(uint16).max; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked * @param nfts an array stored the NFT id that holder staked */ event Staked(address indexed _by, address indexed _from, uint256 amount, uint256[] nfts); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked * @param nfts an array which stored the unstaked NFT id */ event Unstaked(address indexed _by, address indexed _to, uint256 amount, uint256[] nfts); /** * @dev Fired in _unstakeReward() and unstakeReward() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of rewards unstaked */ event UnstakedReward(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerToken updated yield rewards per token value * @param lastYieldDistribution usually, current block number */ event Synchronized(address indexed _by, uint256 yieldRewardsPerToken, uint256 lastYieldDistribution); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, uint256 amount); /** * @dev construct the pool * * @param _high HIGH ERC20 Token address * @param _poolToken token ERC721 the pool operates on, here is the Duck NFT * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _endBlock block number when farming stops and rewards cannot be updated anymore * @param _highPerBlock HIGH/block value for rewards */ constructor( address _high, address _poolToken, uint256 _initBlock, uint256 _endBlock, uint256 _highPerBlock ) { // verify the inputs are set require(_high != address(0), "high token address not set"); require(_poolToken != address(0), "pool token address not set"); require(_initBlock >= blockNumber(), "Invalid init block"); // save the inputs into internal state variables HIGH = _high; poolToken = _poolToken; highPerBlock = _highPerBlock; // init the dependent internal state variables lastYieldDistribution = _initBlock; endBlock = _endBlock; } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view returns (uint256) { // `newYieldRewardsPerToken` will store stored or recalculated value for `yieldRewardsPerToken` uint256 newYieldRewardsPerToken; // if smart contract state was not updated recently, `yieldRewardsPerToken` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (blockNumber() > lastYieldDistribution && usersLockingAmount != 0) { uint256 multiplier = blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution; uint256 highRewards = multiplier * highPerBlock; // recalculated value for `yieldRewardsPerToken` newYieldRewardsPerToken = rewardToToken(highRewards, usersLockingAmount) + yieldRewardsPerToken; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerToken = yieldRewardsPerToken; } // based on the rewards per token value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = tokenToReward(user.tokenAmount, newYieldRewardsPerToken) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns the NFT id on the given index and address * * @dev See getNftListLength * * @param _user an address to query deposit for * @param _index zero-indexed ID for the address specified * @return nft id sotred */ function getNftId(address _user, uint256 _index) external view returns (int32) { // read deposit at specified index and return uint16 value = users[_user].list[_index]; if(value == 0) { return -1; } else if(value == UINT_16_MAX) { return 0; } else { return int32(uint32(value)); } } /** * @notice Returns number of nfts for the given address. Allows iteration over nfts. * * @dev See getNftId * * @param _user an address to query deposit length for * @return number of nfts for the given address */ function getNftsLength(address _user) external view returns (uint256) { // read deposits array length and return return users[_user].list.length; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Returns a batch of deposits on the given pageId for the given address * * @dev We separate deposits into serveral of pages, and each page have DEPOSIT_BATCH_SIZE of item. * * @param _user an address to query deposit for * @param _pageId zero-indexed page ID for the address specified * @return deposits info as Deposit structure */ function getDepositsBatch(address _user, uint256 _pageId) external view returns (Deposit[] memory) { uint256 pageStart = _pageId * DEPOSIT_BATCH_SIZE; uint256 pageEnd = (_pageId + 1) * DEPOSIT_BATCH_SIZE; uint256 pageLength = DEPOSIT_BATCH_SIZE; if(pageEnd > (users[_user].deposits.length - pageStart)) { pageEnd = users[_user].deposits.length; pageLength = pageEnd - pageStart; } Deposit[] memory deposits = new Deposit[](pageLength); for(uint256 i = pageStart; i < pageEnd; ++i) { deposits[i-pageStart] = users[_user].deposits[i]; } return deposits; } /** * @notice Returns number of pages for the given address. Allows iteration over deposits. * * @dev See getDepositsBatch * * @param _user an address to query deposit length for * @return number of pages for the given address */ function getDepositsBatchLength(address _user) external view returns (uint256) { if(users[_user].deposits.length == 0) { return 0; } return 1 + (users[_user].deposits.length - 1) / DEPOSIT_BATCH_SIZE; } /** * @notice Returns a batch of NFT id on the given pageId for the given address * * @dev We separate NFT id into serveral of pages, and each page have NFT_BATCH_SIZE of ids. * * @param _user an address to query deposit for * @param _pageId zero-indexed page ID for the address specified * @return nft ids that holder staked */ function getNftsBatch(address _user, uint256 _pageId) external view returns (int32[] memory) { uint256 pageStart = _pageId * NFT_BATCH_SIZE; uint256 pageEnd = (_pageId + 1) * NFT_BATCH_SIZE; uint256 pageLength = NFT_BATCH_SIZE; if(pageEnd > (users[_user].list.length - pageStart)) { pageEnd = users[_user].list.length; pageLength = pageEnd - pageStart; } int32[] memory list = new int32[](pageLength); uint16 value; for(uint256 i = pageStart; i < pageEnd; ++i) { value = users[_user].list[i]; if(value == 0) { list[i-pageStart] = -1; } else if(value == UINT_16_MAX) { list[i-pageStart] = 0; } else { list[i-pageStart] = int32(uint32(value)); } } return list; } /** * @notice Returns number of pages for the given address. Allows iteration over nfts. * * @dev See getNftsBatch * * @param _user an address to query NFT id length for * @return number of pages for the given address */ function getNftsBatchLength(address _user) external view returns (uint256) { if(users[_user].list.length == 0) { return 0; } return 1 + (users[_user].list.length - 1) / NFT_BATCH_SIZE; } /** * @notice Stakes specified NFT ids * * @dev Requires amount to stake to be greater than zero * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` * * @param _nftIds array of NFTs to stake */ function stake( uint256[] calldata _nftIds ) external nonReentrant { require(!isPoolDisabled(), "Pool disable"); // delegate call to an internal function _stake(msg.sender, _nftIds); } /** * @notice Unstakes specified amount of NFTs, and pays pending yield rewards * * @dev Requires amount to unstake to be greater than zero * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` * * @param _listIds index ID to unstake from, zero-indexed */ function unstake( uint256[] calldata _listIds ) external nonReentrant { // delegate call to an internal function _unstake(msg.sender, _listIds); } /** * @notice Unstakes specified amount of rewards * * @dev Requires amount to unstake to be greater than zero * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` * * @param _depositId deposit ID to unstake from, zero-indexed */ function unstakeReward( uint256 _depositId ) external nonReentrant { // delegate call to an internal function User storage user = users[msg.sender]; Deposit memory stakeDeposit = user.deposits[_depositId]; require(now256() > stakeDeposit.lockedUntil, "deposit not yet unlocked"); _unstakeReward(msg.sender, _depositId); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after end block * ), function doesn't throw and exits silently */ function sync() external { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when staking and unstaking, executes sync() under the hood * before making further calculations and payouts * @dev When timing conditions are not met (executed too frequently, or after end block * ), function doesn't throw and exits silently * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` * */ function processRewards() external virtual nonReentrant { // delegate call to an internal function _processRewards(msg.sender, true); } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return tokenToReward(user.tokenAmount, yieldRewardsPerToken) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _nftIds array of NFTs staked */ function _stake( address _staker, uint256[] calldata _nftIds ) internal virtual { require(_nftIds.length > 0, "zero amount"); // limit the max nft transfer. require(_nftIds.length <= 40, "length exceeds limitation"); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, false); } //looping transfer uint256 addedAmount; for(uint i; i < _nftIds.length; ++i) { IERC721(poolToken).safeTransferFrom(_staker, address(this), _nftIds[i]); if(_nftIds[i] == 0) { //if nft id ==0, then set it to uint16 max user.list.push(UINT_16_MAX); } else { user.list.push(uint16(_nftIds[i])); } addedAmount = addedAmount + 1; } user.tokenAmount += addedAmount; user.subYieldRewards = tokenToReward(user.tokenAmount, yieldRewardsPerToken); usersLockingAmount += addedAmount; // emit an event emit Staked(msg.sender, _staker, addedAmount, _nftIds); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes NFT (which has staked some NFTs earlier) * @param _listIds index ID to unstake from, zero-indexed */ function _unstake( address _staker, uint256[] calldata _listIds ) internal virtual { require(_listIds.length > 0, "zero amount"); // limit the max nft transfer. require(_listIds.length <= 40, "length exceeds limitation"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; uint16[] memory list = user.list; uint256 amount = _listIds.length; require(user.tokenAmount >= amount, "amount exceeds stake"); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, false); // update user record user.tokenAmount -= amount; user.subYieldRewards = tokenToReward(user.tokenAmount, yieldRewardsPerToken); usersLockingAmount = usersLockingAmount - amount; uint256 index; uint256[] memory nfts = new uint256[](_listIds.length); for(uint i; i < _listIds.length; ++i) { index = _listIds[i]; if(UINT_16_MAX == list[index]) { nfts[i] = 0; } else { nfts[i] = uint256(list[index]); } IERC721(poolToken).safeTransferFrom(address(this), _staker, nfts[i]); if (user.tokenAmount != 0) { delete user.list[index]; } } if (user.tokenAmount == 0) { delete user.list; } // emit an event emit Unstaked(msg.sender, _staker, amount, nfts); } /** * @dev Used internally, mostly by children implementations, see unstakeReward() * * @param _staker an address to withraw the yield reward * @param _depositId deposit ID to unstake from, zero-indexed */ function _unstakeReward( address _staker, uint256 _depositId ) internal virtual { // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; uint256 amount = stakeDeposit.rewardAmount; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(amount >= 0, "amount exceeds stake"); // delete deposit if its depleted delete user.deposits[_depositId]; // update user record user.rewardAmount -= amount; // transfer HIGH tokens as required SafeERC20.safeTransfer(IERC20(HIGH), _staker, amount); // emit an event emit UnstakedReward(msg.sender, _staker, amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerToken`, `lastYieldDistribution`) */ function _sync() internal virtual { // check bound conditions and if these are not met - // exit silently, without emitting an event if (lastYieldDistribution >= endBlock) { return; } if (blockNumber() <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingAmount == 0) { lastYieldDistribution = blockNumber(); return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber(); uint256 blocksPassed = currentBlock - lastYieldDistribution; // calculate the reward uint256 highReward = blocksPassed * highPerBlock; // update rewards per weight and `lastYieldDistribution` yieldRewardsPerToken += rewardToToken(highReward, usersLockingAmount); lastYieldDistribution = currentBlock; // emit an event emit Synchronized(msg.sender, yieldRewardsPerToken, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated */ function _processRewards( address _staker, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // create new HIGH deposit // and save it - push it into deposits array Deposit memory newDeposit = Deposit({ rewardAmount: pendingYield, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days) // staking yield for 1 year }); user.deposits.push(newDeposit); // update user record user.rewardAmount += pendingYield; // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = tokenToReward(user.tokenAmount, yieldRewardsPerToken); } // emit an event emit YieldClaimed(msg.sender, _staker, pendingYield); } /** * @dev Converts stake token (not to be mixed with the pool token) to * HIGH reward value, applying the 10^24 division on token * * @param _token stake token * @param _rewardPerToken HIGH reward per token * @return reward value normalized to 10^24 */ function tokenToReward(uint256 _token, uint256 _rewardPerToken) public pure returns (uint256) { // apply the formula and return return (_token * _rewardPerToken) / REWARD_PER_TOKEN_MULTIPLIER; } /** * @dev Converts reward HIGH value to stake token (not to be mixed with the pool token), * applying the 10^24 multiplication on the reward * * @param _reward yield reward * @param _rewardPerToken staked token amount * @return reward/token */ function rewardToToken(uint256 _reward, uint256 _rewardPerToken) public pure returns (uint256) { // apply the reverse formula and return return (_reward * REWARD_PER_TOKEN_MULTIPLIER) / _rewardPerToken; } /** * @notice The function to check pool state. pool is considered "disabled" * once time reaches its "end block" * * @return true if pool is disabled (time has reached end block), false otherwise */ function isPoolDisabled() public view returns (bool) { // verify the pool expiration condition and return the result return blockNumber() >= endBlock; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to time in helper test smart contracts * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now256() public view virtual returns (uint256) { // return current block timestamp return block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.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 "../../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; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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 Used internally, mostly by children implementations, see processRewards() @param _staker an address which receives the reward (which has staked some tokens earlier) @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false @return pendingYield the rewards calculated/ update smart contract state if required update users's record for `subYieldRewards` if requested
function _processRewards( address _staker, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { if (_withUpdate) { _sync(); } Deposit({ rewardAmount: pendingYield, lockedFrom: uint64(now256()), }); user.deposits.push(newDeposit); if (_withUpdate) { user.subYieldRewards = tokenToReward(user.tokenAmount, yieldRewardsPerToken); } }
13,030,055
[ 1, 6668, 12963, 16, 23958, 635, 2325, 16164, 16, 2621, 1207, 17631, 14727, 1435, 225, 389, 334, 6388, 392, 1758, 1492, 17024, 326, 19890, 261, 12784, 711, 384, 9477, 2690, 2430, 13805, 13, 225, 389, 1918, 1891, 2982, 15632, 358, 4056, 24488, 261, 5946, 3792, 10756, 309, 444, 358, 629, 327, 4634, 16348, 326, 283, 6397, 8894, 19, 1089, 13706, 6835, 919, 309, 1931, 1089, 3677, 1807, 1409, 364, 1375, 1717, 16348, 17631, 14727, 68, 309, 3764, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2567, 17631, 14727, 12, 203, 3639, 1758, 389, 334, 6388, 16, 203, 3639, 1426, 389, 1918, 1891, 203, 565, 262, 2713, 5024, 1135, 261, 11890, 5034, 4634, 16348, 13, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 389, 8389, 5621, 203, 3639, 289, 203, 203, 203, 203, 203, 5411, 4019, 538, 305, 12590, 203, 7734, 19890, 6275, 30, 4634, 16348, 16, 203, 7734, 8586, 1265, 30, 2254, 1105, 12, 3338, 5034, 1435, 3631, 203, 5411, 15549, 203, 3639, 729, 18, 323, 917, 1282, 18, 6206, 12, 2704, 758, 1724, 1769, 203, 203, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 729, 18, 1717, 16348, 17631, 14727, 273, 1147, 774, 17631, 1060, 12, 1355, 18, 2316, 6275, 16, 2824, 17631, 14727, 2173, 1345, 1769, 203, 3639, 289, 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 ]
./partial_match/4/0x80cF29796fDcf07f1Cff00663c41D91eEEd6572a/sources/OptionFactory.sol
do sub first as a check since should be positive
amountIn = costAfter.sub(lastCost).add(poolAmountIn);
8,504,868
[ 1, 2896, 720, 1122, 487, 279, 866, 3241, 1410, 506, 6895, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 3844, 382, 273, 6991, 4436, 18, 1717, 12, 2722, 8018, 2934, 1289, 12, 6011, 6275, 382, 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 ]
/* * Kryptium Oracle Smart Contract v.1.0.0 * Copyright © 2018 Kryptium Team <[email protected]> * Author: Giannis Zarifis <[email protected]> * * The Oracle smart contract is used by the House smart contract (and, in turn, * the betting app) as a “trusted source of truth” for upcoming events and their * outcomes. It is managed by an entity trusted by the owner of the House. * * This program is free to use according the Terms and Conditions available at * <https://kryptium.io/terms-and-conditions/>. You cannot resell it or copy any * part of it or modify it without permission from the Kryptium Team. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the Terms and Conditions for more details. */ pragma solidity ^0.5.0; /** * SafeMath * Math operations with safety checks that throw on error */ contract 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; } function mulByFraction(uint256 number, uint256 numerator, uint256 denominator) internal pure returns (uint256) { return div(mul(number, numerator), denominator); } } contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0x0)); owner = newOwner; } } /* * Kryptium Oracle Smart Contract. */ contract Oracle is SafeMath, Owned { enum EventOutputType { stringarray, numeric } uint private eventNextId; uint private subcategoryNextId; struct Event { uint id; string title; uint startDateTime; uint endDateTime; uint subcategoryId; uint categoryId; uint closeDateTime; uint freezeDateTime; bool isCancelled; string announcement; uint totalAvailableOutputs; } struct EventOutcome { uint256 outcome1; uint256 outcome2; uint256 outcome3; uint256 outcome4; uint256 outcome5; uint256 outcome6; } struct EventOutput { bool isSet; string title; uint possibleResultsCount; EventOutputType eventOutputType; string announcement; uint decimals; } struct OracleData { string name; string creatorName; uint closeBeforeStartTime; uint closeEventOutcomeTime; uint version; } struct Subcategory { uint id; uint categoryId; string name; string country; bool hidden; } OracleData public oracleData; // This creates an array with all sucategories mapping (uint => Subcategory) public subcategories; // This creates an array with all events mapping (uint => Event) public events; // Event output possible results mapping (uint =>mapping (uint => mapping (uint => bytes32))) public eventOutputPossibleResults; // Event output Outcome mapping (uint => mapping (uint => EventOutput)) public eventOutputs; //Event output outcome mapping (uint => mapping (uint => uint)) public eventOutcome; //Event output outcome numeric mapping (uint => mapping (uint => EventOutcome)) public eventNumericOutcomes; // Notifies clients that a new Oracle was launched event OracleCreated(); // Notifies clients that the details of an Oracle were changed event OraclePropertiesUpdated(); // Notifies clients that an Oracle subcategory was added event OracleSubcategoryAdded(uint id); // Notifies clients that an Oracle subcategory was changed event OracleSubcategoryUpdated(uint id); // Notifies clients that an Oracle Event was changed event UpcomingEventUpdated(uint id,uint closeDateTime); /** * Constructor function * Initializes Oracle contract */ constructor(string memory oracleName, string memory oracleCreatorName, uint closeBeforeStartTime, uint closeEventOutcomeTime, uint version) public { oracleData.name = oracleName; oracleData.creatorName = oracleCreatorName; oracleData.closeBeforeStartTime = closeBeforeStartTime; oracleData.closeEventOutcomeTime = closeEventOutcomeTime; oracleData.version = version; emit OracleCreated(); } /** * Update Oracle Data function * * Updates Oracle Data */ function updateOracleNames(string memory newName, string memory newCreatorName) onlyOwner public { oracleData.name = newName; oracleData.creatorName = newCreatorName; emit OraclePropertiesUpdated(); } /** * Update Oracle Time Constants function * * Updates Oracle Time Constants */ function setTimeConstants(uint closeBeforeStartTime, uint closeEventOutcomeTime) onlyOwner public { oracleData.closeBeforeStartTime = closeBeforeStartTime; oracleData.closeEventOutcomeTime = closeEventOutcomeTime; emit OraclePropertiesUpdated(); } /** * Adds an Oracle Subcategory */ function setSubcategory(uint id, uint categoryId, string memory name,string memory country,bool hidden) onlyOwner public { if (id==0) { subcategoryNextId += 1; id = subcategoryNextId; } subcategories[id].id = id; subcategories[id].categoryId = categoryId; subcategories[id].name = name; subcategories[id].country = country; subcategories[id].hidden = hidden; emit OracleSubcategoryAdded(id); } /** * Hides an Oracle Subcategory */ function hideSubcategory(uint id) onlyOwner public { subcategories[id].hidden = true; emit OracleSubcategoryUpdated(id); } /** * Adds an Upcoming Event */ function addUpcomingEvent(uint id, string memory title, uint startDateTime, uint endDateTime, uint subcategoryId, uint categoryId, string memory outputTitle, EventOutputType eventOutputType, bytes32[] memory _possibleResults,uint decimals) onlyOwner public { if (id==0) { eventNextId += 1; id = eventNextId; } uint closeDateTime = startDateTime - oracleData.closeBeforeStartTime * 1 minutes; uint freezeDateTime = endDateTime + oracleData.closeEventOutcomeTime * 1 minutes; require(closeDateTime >= now,"Close time should be greater than now"); events[id].id = id; events[id].title = title; events[id].startDateTime = startDateTime; events[id].endDateTime = endDateTime; events[id].subcategoryId = subcategoryId; events[id].categoryId = categoryId; events[id].closeDateTime = closeDateTime; events[id].freezeDateTime = freezeDateTime; eventOutputs[id][0].title = outputTitle; eventOutputs[id][0].possibleResultsCount = _possibleResults.length; eventOutputs[id][0].eventOutputType = eventOutputType; eventOutputs[id][0].decimals = decimals; for (uint j = 0; j<_possibleResults.length; j++) { eventOutputPossibleResults[id][0][j] = _possibleResults[j]; } if (events[id].totalAvailableOutputs < 1) { events[id].totalAvailableOutputs = 1; } emit UpcomingEventUpdated(id,closeDateTime); } /** * Adds a new output to existing an Upcoming Event */ function addUpcomingEventOutput(uint id, string memory outputTitle, EventOutputType eventOutputType, bytes32[] memory _possibleResults,uint decimals) onlyOwner public { require(events[id].closeDateTime >= now,"Close time should be greater than now"); eventOutputs[id][events[id].totalAvailableOutputs].title = outputTitle; eventOutputs[id][events[id].totalAvailableOutputs].possibleResultsCount = _possibleResults.length; eventOutputs[id][events[id].totalAvailableOutputs].eventOutputType = eventOutputType; eventOutputs[id][events[id].totalAvailableOutputs].decimals = decimals; for (uint j = 0; j<_possibleResults.length; j++) { eventOutputPossibleResults[id][events[id].totalAvailableOutputs][j] = _possibleResults[j]; } events[id].totalAvailableOutputs += 1; emit UpcomingEventUpdated(id,events[id].closeDateTime); } /** * Updates an Upcoming Event */ function updateUpcomingEvent(uint id, string memory title, uint startDateTime, uint endDateTime, uint subcategoryId, uint categoryId) onlyOwner public { uint closeDateTime = startDateTime - oracleData.closeBeforeStartTime * 1 minutes; uint freezeDateTime = endDateTime + oracleData.closeEventOutcomeTime * 1 minutes; events[id].title = title; events[id].startDateTime = startDateTime; events[id].endDateTime = endDateTime; events[id].subcategoryId = subcategoryId; events[id].categoryId = categoryId; events[id].closeDateTime = closeDateTime; events[id].freezeDateTime = freezeDateTime; if (closeDateTime < now) { events[id].isCancelled = true; } emit UpcomingEventUpdated(id,closeDateTime); } /** * Cancels an Upcoming Event */ function cancelUpcomingEvent(uint id) onlyOwner public { require(events[id].freezeDateTime >= now,"Freeze time should be greater than now"); events[id].isCancelled = true; emit UpcomingEventUpdated(id,events[id].closeDateTime); } /** * Set the numeric type outcome of Event output */ function setEventOutcomeNumeric(uint eventId, uint outputId, string memory announcement, bool setEventAnnouncement, uint256 outcome1, uint256 outcome2,uint256 outcome3,uint256 outcome4, uint256 outcome5, uint256 outcome6) onlyOwner public { require(events[eventId].freezeDateTime > now,"Freeze time should be greater than now"); require(!events[eventId].isCancelled,"Cancelled Event"); require(eventOutputs[eventId][outputId].eventOutputType == EventOutputType.numeric,"Required numeric Event type"); eventNumericOutcomes[eventId][outputId].outcome1 = outcome1; eventNumericOutcomes[eventId][outputId].outcome2 = outcome2; eventNumericOutcomes[eventId][outputId].outcome3 = outcome3; eventNumericOutcomes[eventId][outputId].outcome4 = outcome4; eventNumericOutcomes[eventId][outputId].outcome5 = outcome5; eventNumericOutcomes[eventId][outputId].outcome6 = outcome6; eventOutputs[eventId][outputId].isSet = true; eventOutputs[eventId][outputId].announcement = announcement; if (setEventAnnouncement) { events[eventId].announcement = announcement; } emit UpcomingEventUpdated(eventId,events[eventId].closeDateTime); } /** * Set the outcome of Event output */ function setEventOutcome(uint eventId, uint outputId, string memory announcement, bool setEventAnnouncement, uint _eventOutcome ) onlyOwner public { require(events[eventId].freezeDateTime > now,"Freeze time should be greater than now"); require(!events[eventId].isCancelled,"Cancelled Event"); require(eventOutputs[eventId][outputId].eventOutputType == EventOutputType.stringarray,"Required array of options Event type"); eventOutputs[eventId][outputId].isSet = true; eventOutcome[eventId][outputId] = _eventOutcome; eventOutputs[eventId][outputId].announcement = announcement; if (setEventAnnouncement) { events[eventId].announcement = announcement; } emit UpcomingEventUpdated(eventId,events[eventId].closeDateTime); } /** * set a new freeze datetime of an Event */ function freezeEventOutcome(uint id, uint newFreezeDateTime) onlyOwner public { require(!events[id].isCancelled,"Cancelled Event"); if (newFreezeDateTime > now) { events[id].freezeDateTime = newFreezeDateTime; } else { events[id].freezeDateTime = now; } emit UpcomingEventUpdated(id,events[id].closeDateTime); } /** * Get event outcome numeric */ function getEventOutcomeNumeric(uint eventId, uint outputId) public view returns(uint256 outcome1, uint256 outcome2,uint256 outcome3,uint256 outcome4, uint256 outcome5, uint256 outcome6) { require(eventOutputs[eventId][outputId].isSet && eventOutputs[eventId][outputId].eventOutputType==EventOutputType.numeric); return (eventNumericOutcomes[eventId][outputId].outcome1,eventNumericOutcomes[eventId][outputId].outcome2,eventNumericOutcomes[eventId][outputId].outcome3,eventNumericOutcomes[eventId][outputId].outcome4,eventNumericOutcomes[eventId][outputId].outcome5,eventNumericOutcomes[eventId][outputId].outcome6); } /** * Get event outcome */ function getEventOutcome(uint eventId, uint outputId) public view returns(uint outcome) { require(eventOutputs[eventId][outputId].isSet && eventOutputs[eventId][outputId].eventOutputType==EventOutputType.stringarray); return (eventOutcome[eventId][outputId]); } /** * Get event outcome is Set */ function getEventOutcomeIsSet(uint eventId, uint outputId) public view returns(bool isSet) { return (eventOutputs[eventId][outputId].isSet); } /** * Get event Info for Houses */ function getEventForHousePlaceBet(uint id) public view returns(uint closeDateTime, uint freezeDateTime, bool isCancelled) { return (events[id].closeDateTime,events[id].freezeDateTime, events[id].isCancelled); } }
Event output possible results
mapping (uint =>mapping (uint => mapping (uint => bytes32))) public eventOutputPossibleResults;
15,809,394
[ 1, 1133, 876, 3323, 1686, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 11890, 516, 6770, 261, 11890, 516, 2874, 261, 11890, 516, 1731, 1578, 20349, 1071, 871, 1447, 13576, 3447, 31, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x628015A6f2e6da491Ad572210C264107DB294f6E/sources/contracts/LowGasVRF1/Lean/ETHFixedLean.sol
@param _desiredFundsInWeis the amount the seller would like to get from the raffle @param _collateralAddress The address of the NFT of the raffle @param _collateralId The id of the NFT (ERC721) @param _minimumFundsInWeis The mininum amount required for the raffle to set a winner @param _prices Array of prices and amount of entries the customer could purchase / @param _commissionInBasicPoints commission for the platform, in basic points @notice Creates a raffle @dev creates a raffle struct and push it to the raffles array. Some data is stored in the funding data structure sends an event when finished @return raffleId Initialize the entries list array, by adding a player and removing it
function createRaffle( uint128 _desiredFundsInWeis, uint256 _prizeNumber, uint128 _minimumFundsInWeis, PriceStructure[] calldata _prices, uint48 _commissionInBasicPoints, ENTRY_TYPE _entryType ) external onlyRole(OPERATOR_ROLE) returns (uint256) { require(_commissionInBasicPoints <= 5000, "commission too high"); RaffleStruct memory raffle = RaffleStruct({ prizeNumber: _prizeNumber, winner: address(0), randomNumber: 0, seller: address(0), platformPercentage: _commissionInBasicPoints }); raffles.push(raffle); saveEntryInfo(_entryType); uint256 idRaffle = raffles.length - 1; require(_prices.length > 0, "No prices"); for (uint256 i = 0; i < _prices.length; i++) { require(_prices[i].numEntries > 0, "numEntries is 0"); PriceStructure memory p = PriceStructure({ id: idRaffle, numEntries: _prices[i].numEntries, price: _prices[i].price }); pricesList[_prices[i].id] = p; } fundingList[idRaffle] = FundingStructure({ minimumFundsInWeis: _minimumFundsInWeis, desiredFundsInWeis: _desiredFundsInWeis }); emit RaffleCreated(idRaffle, _prizeNumber); EntriesBought memory entryBought = EntriesBought({ player: msg.sender, currentEntriesLength: uint48(1) }); entriesList[idRaffle].push(entryBought); delete entriesList[idRaffle][0]; return idRaffle; }
15,977,908
[ 1, 67, 30458, 42, 19156, 382, 3218, 291, 326, 3844, 326, 29804, 4102, 3007, 358, 336, 628, 326, 767, 1403, 298, 225, 389, 12910, 2045, 287, 1887, 1021, 1758, 434, 326, 423, 4464, 434, 326, 767, 1403, 298, 225, 389, 12910, 2045, 287, 548, 1021, 612, 434, 326, 423, 4464, 261, 654, 39, 27, 5340, 13, 225, 389, 15903, 42, 19156, 382, 3218, 291, 1021, 1131, 267, 379, 3844, 1931, 364, 326, 767, 1403, 298, 358, 444, 279, 5657, 1224, 225, 389, 683, 1242, 1510, 434, 19827, 471, 3844, 434, 3222, 326, 6666, 3377, 23701, 282, 342, 225, 389, 832, 3951, 382, 8252, 5636, 1543, 19710, 364, 326, 4072, 16, 316, 5337, 3143, 225, 10210, 279, 767, 1403, 298, 225, 3414, 279, 767, 1403, 298, 1958, 471, 1817, 518, 358, 326, 767, 1403, 1040, 526, 18, 10548, 501, 353, 4041, 316, 326, 22058, 501, 3695, 9573, 392, 871, 1347, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 752, 54, 7329, 298, 12, 203, 3639, 2254, 10392, 389, 30458, 42, 19156, 382, 3218, 291, 16, 203, 3639, 2254, 5034, 389, 683, 554, 1854, 16, 203, 3639, 2254, 10392, 389, 15903, 42, 19156, 382, 3218, 291, 16, 203, 3639, 20137, 6999, 8526, 745, 892, 389, 683, 1242, 16, 203, 3639, 2254, 8875, 389, 832, 3951, 382, 8252, 5636, 16, 203, 3639, 25516, 67, 2399, 389, 4099, 559, 203, 565, 262, 3903, 1338, 2996, 12, 26110, 67, 16256, 13, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 24899, 832, 3951, 382, 8252, 5636, 1648, 20190, 16, 315, 832, 3951, 4885, 3551, 8863, 203, 203, 3639, 534, 7329, 298, 3823, 3778, 767, 1403, 298, 273, 534, 7329, 298, 3823, 12590, 203, 5411, 846, 554, 1854, 30, 389, 683, 554, 1854, 16, 203, 5411, 5657, 1224, 30, 1758, 12, 20, 3631, 203, 5411, 2744, 1854, 30, 374, 16, 203, 5411, 29804, 30, 1758, 12, 20, 3631, 203, 5411, 4072, 16397, 30, 389, 832, 3951, 382, 8252, 5636, 203, 3639, 15549, 203, 3639, 767, 1403, 1040, 18, 6206, 12, 354, 1403, 298, 1769, 203, 203, 3639, 1923, 1622, 966, 24899, 4099, 559, 1769, 203, 203, 3639, 2254, 5034, 612, 54, 7329, 298, 273, 767, 1403, 1040, 18, 2469, 300, 404, 31, 203, 203, 3639, 2583, 24899, 683, 1242, 18, 2469, 405, 374, 16, 315, 2279, 19827, 8863, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 683, 1242, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 24899, 683, 1242, 2 ]
pragma solidity >0.5.4; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "@daostack/arc/contracts/controller/Avatar.sol"; import "../../contracts/dao/schemes/FeelessScheme.sol"; import "../../contracts/identity/Identity.sol"; import "../../contracts/DSMath.sol"; interface cERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 mintAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function balanceOf(address addr) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); } /** * @title Staking contract that donates earned interest to the DAO * allowing stakers to deposit DAI or withdraw their stake in DAI. * The contract buys cDAI and can transfer the daily interest to the DAO */ contract SimpleDAIStaking is DSMath, Pausable, FeelessScheme { using SafeMath for uint256; // Entity that holds a staker info struct Staker { // The staked DAI amount uint256 stakedDAI; // The latest block number which the // staker has staked tokens uint256 lastStake; } // The map which holds the stakers entities mapping(address => Staker) public stakers; // Emits when new DAI tokens have been staked event DAIStaked( // The staker address address indexed staker, // How many tokens have been staked uint256 daiValue ); // Emits when DAI tokens are being withdrawn event DAIStakeWithdraw( // The staker that initiate the action address indexed staker, // The initial DAI value that was staked uint256 daiValue, // The current DAI value that was staked uint256 daiActual ); // Emits when the interest is collected event InterestCollected( // Who is receives the interest address recipient, // How many cDAI tokens have been transferred uint256 cdaiValue, // The worth of the transferred tokens in DAI uint256 daiValue, // Lost amount. A result of different precisions uint256 daiPrecisionLoss ); // DAI token address ERC20 public dai; // cDAI token address cERC20 public cDai; // The block interval defines the number of // blocks that shall be passed before the // next execution of `collectUBIInterest` uint256 public blockInterval; // The last block number which // `collectUBIInterest` has been executed in uint256 public lastUBICollection; // The total staked DAI amount in the contract uint256 public totalStaked = 0; // How much of the generated interest is donated, // meaning no GD is expected in compensation, 1 in mil precision. // 100% for phase0 POC uint32 public avgInterestDonatedRatio = 1e6; // The address of the fund manager contract address public fundManager; modifier onlyFundManager { require(msg.sender == fundManager, "Only FundManager can call this method"); _; } /** * @dev Constructor * @param _dai The address of DAI * @param _cDai The address of cDAI * @param _fundManager The address of the fund manager contract * @param _blockInterval How many blocks should be passed before the next execution of `collectUBIInterest` * @param _avatar The avatar of the DAO * @param _identity The identity contract */ constructor( address _dai, address _cDai, address _fundManager, uint256 _blockInterval, Avatar _avatar, Identity _identity ) public FeelessScheme(_identity, _avatar) { dai = ERC20(_dai); cDai = cERC20(_cDai); blockInterval = _blockInterval; lastUBICollection = block.number.div(blockInterval); fundManager = _fundManager; // Adds the avatar as a pauser of this contract addPauser(address(avatar)); } /** * @dev Allows the DAO to change the fund manager contract address * @param _fundManager Address of the new contract */ function setFundManager(address _fundManager) public onlyAvatar { fundManager = _fundManager; } /** * @dev Allows a staker to deposit DAI tokens. Notice that `approve` is * needed to be executed before the execution of this method. * Can be executed only when the contract is not paused. * @param _amount The amount of DAI to stake */ function stakeDAI(uint256 _amount) public whenNotPaused { require(_amount > 0, "You need to stake a positive token amount"); require( dai.transferFrom(msg.sender, address(this), _amount) == true, "transferFrom failed, make sure you approved DAI transfer" ); // approve the transfer to cDAI dai.approve(address(cDai), _amount); // mint ctokens uint256 res = cDai.mint(_amount); // cDAI returns >0 if error happened while minting. // Makes sure that there are no errors. If an error // has occurred, DAI funds shall be returned. if (res > 0) { require(res == 0, "Minting cDai failed, funds returned"); } // updated the staker entity Staker storage staker = stakers[msg.sender]; staker.stakedDAI = staker.stakedDAI.add(_amount); staker.lastStake = block.number; // adds the staked amount to the total staked totalStaked = totalStaked.add(_amount); emit DAIStaked(msg.sender, _amount); } /** * @dev Withdraws the sender staked DAI. */ function withdrawStake() public { Staker storage staker = stakers[msg.sender]; require(staker.stakedDAI > 0, "No DAI staked"); require(cDai.redeemUnderlying(staker.stakedDAI) == 0, "Failed to redeem cDai"); uint256 daiWithdraw = staker.stakedDAI; // updates balance before transfer to prevent re-entry staker.stakedDAI = 0; totalStaked = totalStaked.sub(daiWithdraw); //redeeming in compound may result in a tiny fraction of precission error //so if we redeem 100 DAI we might get something like 99.9999999999 uint256 daiActual = dai.balanceOf(address(this)); if (daiActual < daiWithdraw) { daiWithdraw = daiActual; } require(dai.transfer(msg.sender, daiWithdraw), "withdraw transfer failed"); emit DAIStakeWithdraw(msg.sender, daiWithdraw, daiActual); } /** * @dev Calculates the worth of the staked cDAI tokens in DAI. * @return (uint256) The worth in DAI */ function currentDAIWorth() public view returns (uint256) { uint256 er = cDai.exchangeRateStored(); //TODO: why 1e10? cDai is e8 so we should convert it to e28 like exchange rate uint256 daiBalance = rmul(cDai.balanceOf(address(this)).mul(1e10), er).div(10); return daiBalance; } /** * @dev Calculates the current interest that was gained. * @return (uint256, uint256, uint256) The interest in cDAI, the interest in DAI, * the amount which is not covered by precision of DAI */ function currentUBIInterest() public view returns ( uint256, uint256, uint256 ) { uint256 er = cDai.exchangeRateStored(); uint256 daiWorth = currentDAIWorth(); if (daiWorth <= totalStaked) { return (0, 0, 0); } uint256 daiGains = daiWorth.sub(totalStaked); // mul by 1e10 to equalize precision otherwise since exchangerate // is very big, dividing by it would result in 0. uint256 cdaiGains = rdiv(daiGains.mul(1e10), er); // gets right most bits not covered by precision of cdai which is // only 8 decimals while RAY is 27 uint256 precisionLossCDaiRay = cdaiGains.mod(1e19); // lower back to 8 decimals cdaiGains = cdaiGains.div(1e19); //div by 1e10 to get results in dai precision 1e18 uint256 precisionLossDai = rmul(precisionLossCDaiRay, er).div(1e10); return (cdaiGains, daiGains, precisionLossDai); } /** * @dev Collects gained interest by fundmanager. Can be collected only once * in an interval which is defined above. * @param _recipient The recipient of cDAI gains * @return (uint256, uint256, uint256, uint32) The interest in cDAI, the interest in DAI, * the amount which is not covered by precision of DAI, how much of the generated interest is donated */ function collectUBIInterest(address _recipient) public onlyFundManager returns ( uint256, uint256, uint256, uint32 ) { // otherwise fund manager has to wait for the next interval require(_recipient != address(this), "Recipient cannot be the staking contract"); require(canCollect(), "Need to wait for the next interval"); ( uint256 cdaiGains, uint256 daiGains, uint256 precisionLossDai ) = currentUBIInterest(); lastUBICollection = block.number.div(blockInterval); if (cdaiGains > 0) require(cDai.transfer(_recipient, cdaiGains), "collect transfer failed"); emit InterestCollected(_recipient, cdaiGains, daiGains, precisionLossDai); return (cdaiGains, daiGains, precisionLossDai, avgInterestDonatedRatio); } /** * @dev Checks if enough blocks have passed so it would be possible to * execute `collectUBIInterest` according to the length of `blockInterval` * @return (bool) True if enough blocks have passed */ function canCollect() public view returns (bool) { return block.number.div(blockInterval) > lastUBICollection; } /** * @dev Start function. Adds this contract to identity as a feeless scheme. * Can only be called if scheme is registered */ function start() public onlyRegistered { addRights(); } /** * @dev making the contract inactive * NOTICE: this could theoretically result in future interest earned in cdai to remain locked * but we dont expect any other stakers but us in SimpleDAIStaking */ function end() public onlyAvatar { pause(); removeRights(); } /** * @dev method to recover any stuck erc20 tokens (ie compound COMP) * @param _token the ERC20 token to recover */ function recover(ERC20 _token) public onlyAvatar { uint256 toWithdraw = _token.balanceOf(address(this)); // recover left cDai(stakers token) only when all stakes have been withdrawn if (address(_token) == address(cDai)) { require( totalStaked == 0 && paused(), "can recover cDai only when stakes have been withdrawn" ); } require(_token.transfer(address(avatar), toWithdraw), "recover transfer failed"); } }
The address of the fund manager contract
address public fundManager;
1,078,854
[ 1, 1986, 1758, 434, 326, 284, 1074, 3301, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 1758, 1071, 284, 1074, 1318, 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 ]
./full_match/4/0xc8639168e2eca333b47F083A029Fe2d36169b221/sources/contracts/Strings.sol
* @dev String operations./
library Strings { bytes16 private constant alphabet = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } 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); } }
13,320,502
[ 1, 780, 5295, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 8139, 288, 203, 565, 1731, 2313, 3238, 5381, 10877, 273, 315, 26684, 28953, 14432, 203, 203, 203, 565, 445, 1762, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 203, 3639, 309, 261, 1132, 422, 374, 13, 288, 203, 5411, 327, 315, 20, 14432, 203, 3639, 289, 203, 3639, 2254, 5034, 1906, 273, 460, 31, 203, 3639, 2254, 5034, 6815, 31, 203, 3639, 1323, 261, 5814, 480, 374, 13, 288, 203, 5411, 6815, 9904, 31, 203, 5411, 1906, 9531, 1728, 31, 203, 3639, 289, 203, 3639, 1731, 3778, 1613, 273, 394, 1731, 12, 16649, 1769, 203, 3639, 1323, 261, 1132, 480, 374, 13, 288, 203, 5411, 6815, 3947, 404, 31, 203, 5411, 1613, 63, 16649, 65, 273, 1731, 21, 12, 11890, 28, 12, 8875, 397, 2254, 5034, 12, 1132, 738, 1728, 3719, 1769, 203, 5411, 460, 9531, 1728, 31, 203, 3639, 289, 203, 3639, 327, 533, 12, 4106, 1769, 203, 565, 289, 203, 203, 565, 445, 1762, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 203, 3639, 309, 261, 1132, 422, 374, 13, 288, 203, 5411, 327, 315, 20, 14432, 203, 3639, 289, 203, 3639, 2254, 5034, 1906, 273, 460, 31, 203, 3639, 2254, 5034, 6815, 31, 203, 3639, 1323, 261, 5814, 480, 374, 13, 288, 203, 5411, 6815, 9904, 31, 203, 5411, 1906, 9531, 1728, 31, 203, 3639, 289, 203, 3639, 1731, 3778, 1613, 273, 394, 1731, 12, 16649, 1769, 203, 3639, 1323, 261, 1132, 480, 374, 13, 288, 203, 5411, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /* ██████╗░██╗██╗░░██╗███████╗██╗░░░░░░█████╗░████████╗██╗░█████╗░███╗░░██╗░██████╗ ██╔══██╗██║╚██╗██╔╝██╔════╝██║░░░░░██╔══██╗╚══██╔══╝██║██╔══██╗████╗░██║██╔════╝ ██████╔╝██║░╚███╔╝░█████╗░░██║░░░░░███████║░░░██║░░░██║██║░░██║██╔██╗██║╚█████╗░ ██╔═══╝░██║░██╔██╗░██╔══╝░░██║░░░░░██╔══██║░░░██║░░░██║██║░░██║██║╚████║░╚═══██╗ ██║░░░░░██║██╔╝╚██╗███████╗███████╗██║░░██║░░░██║░░░██║╚█████╔╝██║░╚███║██████╔╝ ╚═╝░░░░░╚═╝╚═╝░░╚═╝╚══════╝╚══════╝╚═╝░░╚═╝░░░╚═╝░░░╚═╝░╚════╝░╚═╝░░╚══╝╚═════╝░ What are Pixelations? Pixelations are an NFT collection of 32x32 pixelated images. There are 3,232 Pixelations, each 100% stored and rendered on chain. For this collection, we took a unique approach. Rather than designing the art ourselves, we are giving the minter the ability to provide the art. This image could be anything: an IRL photo, a painting, or a JPEG pulled off the internet. How does it work? Upon minting, we perform a number of image processing steps in order to viably store your image on chain, and also reduce minting gas fees as much as possible. At a high level we do the following off chain: 1. Convert the image into 32x32 pixels. 2. Extract the 32 colors that best represent the image via k-means clustering. 3. Compress the image via bit-packing since we now only need 5-bits to represent it's 32 colors. After these off chain steps, your image is roughly 700 bytes of data that we store in our custom ERC-721 smart contract. When sites like OpenSea attempt to fetch your Pixelation's metadata and image, our contract renders an SVG at run-time. ---------------------------------------------------------------------------- Special shoutout to Chainrunners and Blitmap for the inspiration and help. We used a lot of the same techniques in order to perform efficient rendering. */ contract Pixelations is ERC721Enumerable, Ownable, ReentrancyGuard { uint256 public MAX_TOKENS = 3232; mapping(address => uint256) public earlyAccessMintsAllowed; uint256 private constant MAX_PER_EARLY_ACCESS_ADDRESS = 3; mapping(address => uint256) public privateSaleMintsAllowed; uint256 private constant PRIVATE_SALE_MINT_PRICE = 0.025 ether; uint256 private constant MAX_PER_PRIVATE_SALE_ADDRESS = 5; uint256 public publicSaleStartTimestamp; uint256 private constant PUBLIC_SALE_MINT_PRICE = 0.05 ether; uint256 public numberOfMints; bytes[] private _tokenDatas; bytes[] private _colorsByToken; string[32] private _coordinateLookup; bool public mintingCompleteAndValid; struct SVGRowBuffer { string one; string two; string three; string four; string five; string six; string seven; string eight; } struct SVGCursor { uint8 x; uint8 y; string color1; string color2; string color3; string color4; } constructor() ERC721("Pixelations", "PIXELATIONS") { // base64-encoded svg coordinates from 010 to 310 _coordinateLookup = [ "MDAw", "MDEw", "MDIw", "MDMw", "MDQw", "MDUw", "MDYw", "MDcw", "MDgw", "MDkw", "MTAw", "MTEw", "MTIw", "MTMw", "MTQw", "MTUw", "MTYw", "MTcw", "MTgw", "MTkw", "MjAw", "MjEw", "MjIw", "MjMw", "MjQw", "MjUw", "MjYw", "Mjcw", "Mjgw", "Mjkw", "MzAw", "MzEw" ]; } modifier whenPublicSaleActive() { require(isPublicSaleOpen(), "Public sale not open"); _; } function isPublicSaleOpen() public view returns (bool) { return publicSaleStartTimestamp != 0 && block.timestamp >= publicSaleStartTimestamp; } function setPublicSaleStartTimestamp(uint256 timestamp) external onlyOwner { publicSaleStartTimestamp = timestamp; } function mintEarlyAccess(bytes memory tokenData, bytes memory colors) external payable nonReentrant returns (uint256) { require(getRemainingEarlyAccessMints(msg.sender) > 0, "Address has no more early access mints remaining."); earlyAccessMintsAllowed[msg.sender]--; return _mintNewToken(tokenData, colors); } function mintPrivateSale(bytes memory tokenData, bytes memory colors) external payable nonReentrant returns (uint256) { require(getRemainingPrivateSaleMints(msg.sender) > 0, "Address has no more private sale mints remaining."); require(PRIVATE_SALE_MINT_PRICE == msg.value, "Incorrect amount of ether sent."); privateSaleMintsAllowed[msg.sender]--; return _mintNewToken(tokenData, colors); } function mintPublicSale(bytes memory tokenData, bytes memory colors) external payable nonReentrant whenPublicSaleActive returns (uint256) { require(PUBLIC_SALE_MINT_PRICE == msg.value, "Incorrect amount of ether sent."); return _mintNewToken(tokenData, colors); } // tokenData needs to be 640 bytes where every 5 bits represents the color index of a pixel. // colors needs to be 32 hex colors concatenated together. function _mintNewToken(bytes memory tokenData, bytes memory colors) internal returns (uint256) { require(tokenData.length == 640, "tokenData must be 640 bytes."); require(colors.length == 96, "colors must be 96 bytes."); require(numberOfMints < MAX_TOKENS, "All Pixelations have been minted."); _tokenDatas.push(tokenData); _colorsByToken.push(colors); uint256 newItemId = numberOfMints + 1; _safeMint(msg.sender, newItemId); numberOfMints++; return newItemId; } function getRemainingEarlyAccessMints(address addr) public view returns (uint256) { return earlyAccessMintsAllowed[addr]; } function addToEarlyAccessList(address[] memory toEarlyAccessList) external onlyOwner { for (uint256 i = 0; i < toEarlyAccessList.length; i++) { earlyAccessMintsAllowed[toEarlyAccessList[i]] = MAX_PER_EARLY_ACCESS_ADDRESS; } } function getRemainingPrivateSaleMints(address addr) public view returns (uint256) { return privateSaleMintsAllowed[addr]; } function addToPrivateSaleList(address[] memory toPrivateSaleList) external onlyOwner { for (uint256 i = 0; i < toPrivateSaleList.length; i++) { privateSaleMintsAllowed[toPrivateSaleList[i]] = MAX_PER_PRIVATE_SALE_ADDRESS; } } // Hopefully we don't have to use this. But as a safeguard for if somebody needs to change their photo // we have the ability to override the token data. Once all tokens are minted and verified to be valid, we can close // off this functionality with: setMintingCompleteAndValid() function overwriteExistingTokenData( uint256 tokenId, bytes memory tokenData, bytes memory colors ) external onlyOwner { require(tokenId >= 1, "Invalid tokenId."); require(tokenId <= numberOfMints, "Token hasn't been minted yet."); require(tokenData.length == 640, "tokenData must be 640 bytes."); require(colors.length == 96, "tokenData must be 96 bytes."); require(!mintingCompleteAndValid, "You are not allowed to overwrite existing token data anymore."); uint256 tokenIndex = tokenId - 1; _tokenDatas[tokenIndex] = tokenData; _colorsByToken[tokenIndex] = colors; } function setMintingCompleteAndValid() external onlyOwner { mintingCompleteAndValid = true; } // This returns the base64-encoded JSON metadata for the given token. Metadata looks like this: // // { // "image_data": "<svg>...</svg>", // "name": "Pixelation #31", // "description": "A 32x32 pixelated image, stored and rendered completely on chain." // } // // As you'll see in the rest of this contract, we try to keep everything pre base64-encoded. function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { string[4] memory buffer = tokenSvgDataOf(tokenId); return string( abi.encodePacked( "data:application/json;base64,eyAgImltYWdlX2RhdGEiOiAiPHN2ZyB2ZXJzaW9uPScxLjEnIHZpZXdCb3g9JzAgMCAzMjAgMzIwJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHNoYXBlLXJlbmRlcmluZz0nY3Jpc3BFZGdlcyc+", buffer[0], buffer[1], buffer[2], buffer[3], "PHN0eWxlPnJlY3R7d2lkdGg6MTBweDtoZWlnaHQ6MTBweDt9PC9zdHlsZT48L3N2Zz4iLCAgIm5hbWUiOiAiUGl4ZWxhdGlvbiAj", Base64.encode(uintToByteString(tokenId, 6)), "IiwgImRlc2NyaXB0aW9uIjogIkEgMzJ4MzIgcGl4ZWxhdGVkIGltYWdlLCBzdG9yZWQgYW5kIHJlbmRlcmVkIGNvbXBsZXRlbHkgb24gY2hhaW4uIn0g" ) ); } // Handy function for only rendering the svg. function tokenSVG(uint256 tokenId) public view returns (string memory) { string[4] memory buffer = tokenSvgDataOf(tokenId); return string( abi.encodePacked( "PHN2ZyB2ZXJzaW9uPScxLjEnIHZpZXdCb3g9JzAgMCAzMjAgMzIwJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHNoYXBlLXJlbmRlcmluZz0nY3Jpc3BFZGdlcyc+", buffer[0], buffer[1], buffer[2], buffer[3], "PHN0eWxlPnJlY3R7d2lkdGg6MTBweDtoZWlnaHQ6MTBweDt9PC9zdHlsZT48L3N2Zz4" ) ); } function tokenDataOf(uint256 tokenId) public view returns (bytes memory) { return _tokenDatas[tokenId - 1]; } function tokenColors(uint256 tokenId) public view returns (bytes memory) { return _colorsByToken[tokenId - 1]; } // In order to convert the _tokenData and _colorsByToken for a given tokenId, we need // to loop over every pixel, grab the color for that pixel, and generate an svg rect for // that pixel. The difficulty is doing this in a gas efficient manner. // // The naive approach would be to store the output in a string, and continually append // svg rects to that string via abi.encodePacked. However calling abi.encodePacked on // a successively larger output string is expensive. And so the solution here is to // build up a series of buffers of strings. The first buffer contains 8 strings where // each string is a single row of svg rects. The second buffer contains 4 strings // where each string is 8 rows of svg rects (really its just the concatenation of the // previous buffer). // // At the end we return this buffer of 4 strings, and it is up to the caller to concatenate // those strings together in order to form the resulting svg. // // Shoutout to Chainrunners for the help here. function tokenSvgDataOf(uint256 tokenId) private view returns (string[4] memory) { SVGCursor memory cursor; SVGRowBuffer memory cursorRow; string[8] memory bufferOfRows; uint8 indexIntoBufferOfRows; string[4] memory bufferOfEightRows; uint8 indexIntoBufferOfEightRows; for (uint256 dataIndex = 0; dataIndex < 1024; ) { cursor.color1 = getColor(tokenId, dataIndex, 0); cursor.color2 = getColor(tokenId, dataIndex, 1); cursor.color3 = getColor(tokenId, dataIndex, 2); cursor.color4 = getColor(tokenId, dataIndex, 3); cursorRow.one = fourPixels(cursor); cursor.x += 4; cursor.color1 = getColor(tokenId, dataIndex, 4); cursor.color2 = getColor(tokenId, dataIndex, 5); cursor.color3 = getColor(tokenId, dataIndex, 6); cursor.color4 = getColor(tokenId, dataIndex, 7); cursorRow.two = fourPixels(cursor); dataIndex += 8; cursor.x += 4; cursor.color1 = getColor(tokenId, dataIndex, 0); cursor.color2 = getColor(tokenId, dataIndex, 1); cursor.color3 = getColor(tokenId, dataIndex, 2); cursor.color4 = getColor(tokenId, dataIndex, 3); cursorRow.three = fourPixels(cursor); cursor.x += 4; cursor.color1 = getColor(tokenId, dataIndex, 4); cursor.color2 = getColor(tokenId, dataIndex, 5); cursor.color3 = getColor(tokenId, dataIndex, 6); cursor.color4 = getColor(tokenId, dataIndex, 7); cursorRow.four = fourPixels(cursor); dataIndex += 8; cursor.x += 4; cursor.color1 = getColor(tokenId, dataIndex, 0); cursor.color2 = getColor(tokenId, dataIndex, 1); cursor.color3 = getColor(tokenId, dataIndex, 2); cursor.color4 = getColor(tokenId, dataIndex, 3); cursorRow.five = fourPixels(cursor); cursor.x += 4; cursor.color1 = getColor(tokenId, dataIndex, 4); cursor.color2 = getColor(tokenId, dataIndex, 5); cursor.color3 = getColor(tokenId, dataIndex, 6); cursor.color4 = getColor(tokenId, dataIndex, 7); cursorRow.six = fourPixels(cursor); dataIndex += 8; cursor.x += 4; cursor.color1 = getColor(tokenId, dataIndex, 0); cursor.color2 = getColor(tokenId, dataIndex, 1); cursor.color3 = getColor(tokenId, dataIndex, 2); cursor.color4 = getColor(tokenId, dataIndex, 3); cursorRow.seven = fourPixels(cursor); cursor.x += 4; cursor.color1 = getColor(tokenId, dataIndex, 4); cursor.color2 = getColor(tokenId, dataIndex, 5); cursor.color3 = getColor(tokenId, dataIndex, 6); cursor.color4 = getColor(tokenId, dataIndex, 7); cursorRow.eight = fourPixels(cursor); dataIndex += 8; bufferOfRows[indexIntoBufferOfRows++] = string( abi.encodePacked( cursorRow.one, cursorRow.two, cursorRow.three, cursorRow.four, cursorRow.five, cursorRow.six, cursorRow.seven, cursorRow.eight ) ); cursor.x = 0; cursor.y += 1; if (indexIntoBufferOfRows >= 8) { bufferOfEightRows[indexIntoBufferOfEightRows++] = string( abi.encodePacked( bufferOfRows[0], bufferOfRows[1], bufferOfRows[2], bufferOfRows[3], bufferOfRows[4], bufferOfRows[5], bufferOfRows[6], bufferOfRows[7] ) ); indexIntoBufferOfRows = 0; } } return bufferOfEightRows; } // Extracts the base64-encoded hex color for a single pixel. function getColor( uint256 tokenId, uint256 dataIndex, uint256 offset ) internal view returns (string memory) { uint256 pixelIndex = dataIndex + offset; uint256 indexIntoColors = getColorIndexFromPixelIndex(tokenId, pixelIndex); bytes memory rgbBytes = subBytesOfLength3(_colorsByToken[tokenId - 1], indexIntoColors * 3); uint256 n = uint256(uint8(rgbBytes[0])); n = (n << 8) + uint256(uint8(rgbBytes[1])); n = (n << 8) + uint256(uint8(rgbBytes[2])); return Base64.encode(uintToHexBytes6(n)); } // Unpack the 5-bit value representing the color index for a given pixel. A bunch of bitwise operations // needed to pull this off. Code is confusing af, just trust me that the math works out here. function getColorIndexFromPixelIndex(uint256 tokenId, uint256 pixelIndex) internal view returns (uint8) { uint256 indexIntoBytes = (5 * pixelIndex) / 8; uint8 indexIntoByte = uint8((5 * pixelIndex) % 8); bytes memory tokenData = _tokenDatas[tokenId - 1]; uint8 value = 0; uint8 indexedByte = uint8(tokenData[indexIntoBytes]); if (indexIntoByte >= 3) { uint8 mod = uint8(2**(8 - indexIntoByte)); uint8 shift = (indexIntoByte - 3); value = (indexedByte % mod) << shift; } else { uint8 mod = (3 - indexIntoByte); value = (indexedByte >> mod) % 32; } if (indexIntoByte > 3) { uint8 leftoverBits = indexIntoByte - 3; uint8 nextByte = uint8(tokenData[indexIntoBytes + 1]); value += nextByte >> (8 - leftoverBits); } return value; } function subBytesOfLength3(bytes memory bb, uint256 startIndex) internal pure returns (bytes memory) { bytes memory result = new bytes(3); for (uint256 i = startIndex; i < startIndex + 3; i++) { result[i - startIndex] = bb[i]; } return result; } // Rather than constructing each svg rect one at a time, let's save on gas and construct four at a time. // Unfortunately we can't construct more than four pixels at a time, otherwise we would // run into "stack too deep" errors at compile time. // // In order to get this to compile correctly, make sure to have the following compiler settings: // // optimizer: { // enabled: true, // runs: 2000, // details: { // yul: true, // yulDetails: { // stackAllocation: true, // optimizerSteps: "dhfoDgvulfnTUtnIf" // } // } // } function fourPixels(SVGCursor memory pos) internal view returns (string memory) { return string( abi.encodePacked( "PHJlY3QgICBmaWxsPScj", pos.color1, "JyAgeD0n", _coordinateLookup[pos.x], "JyAgeT0n", _coordinateLookup[pos.y], "JyAvPjxyZWN0ICBmaWxsPScj", pos.color2, "JyAgeD0n", _coordinateLookup[pos.x + 1], "JyAgeT0n", _coordinateLookup[pos.y], "JyAvPjxyZWN0ICBmaWxsPScj", pos.color3, "JyAgeD0n", _coordinateLookup[pos.x + 2], "JyAgeT0n", _coordinateLookup[pos.y], "JyAvPjxyZWN0ICBmaWxsPScj", pos.color4, "JyAgeD0n", _coordinateLookup[pos.x + 3], "JyAgeT0n", _coordinateLookup[pos.y], "JyAgIC8+" ) ); } function uintToHexBytes6(uint256 a) public pure returns (bytes memory) { string memory str = uintToHexString2(a); if (bytes(str).length == 2) { return abi.encodePacked("0000", str); } else if (bytes(str).length == 3) { return abi.encodePacked("000", str); } else if (bytes(str).length == 4) { return abi.encodePacked("00", str); } else if (bytes(str).length == 5) { return abi.encodePacked("0", str); } return bytes(str); } /* Convert uint to hex string, padding to 2 hex nibbles */ function uintToHexString2(uint256 a) public pure returns (string memory) { uint256 count = 0; uint256 b = a; while (b != 0) { count++; b /= 16; } bytes memory res = new bytes(count); for (uint256 i = 0; i < count; ++i) { b = a % 16; res[count - i - 1] = uintToHexDigit(uint8(b)); a /= 16; } string memory str = string(res); if (bytes(str).length == 0) { return "00"; } else if (bytes(str).length == 1) { return string(abi.encodePacked("0", str)); } return str; } function uintToHexDigit(uint8 d) public pure returns (bytes1) { if (0 <= d && d <= 9) { return bytes1(uint8(bytes1("0")) + d); } else if (10 <= uint8(d) && uint8(d) <= 15) { return bytes1(uint8(bytes1("a")) + d - 10); } revert(); } function uintToByteString(uint256 a, uint256 fixedLen) internal pure returns (bytes memory _uintAsString) { uint256 j = a; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(fixedLen); j = fixedLen; if (a == 0) { bstr[0] = "0"; len = 1; } while (j > len) { j = j - 1; bstr[j] = bytes1(" "); } uint256 k = len; while (a != 0) { k = k - 1; uint8 temp = (48 + uint8(a - (a / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; a /= 10; } return bstr; } receive() external payable {} function withdraw() public onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Withdrawal failed"); } } library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; uint256 encodedLen = 4 * ((len + 2) / 3); bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.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 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 // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.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); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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); } }
Unpack the 5-bit value representing the color index for a given pixel. A bunch of bitwise operations needed to pull this off. Code is confusing af, just trust me that the math works out here.
function getColorIndexFromPixelIndex(uint256 tokenId, uint256 pixelIndex) internal view returns (uint8) { uint256 indexIntoBytes = (5 * pixelIndex) / 8; uint8 indexIntoByte = uint8((5 * pixelIndex) % 8); bytes memory tokenData = _tokenDatas[tokenId - 1]; uint8 value = 0; uint8 indexedByte = uint8(tokenData[indexIntoBytes]); if (indexIntoByte >= 3) { uint8 mod = uint8(2**(8 - indexIntoByte)); uint8 shift = (indexIntoByte - 3); value = (indexedByte % mod) << shift; uint8 mod = (3 - indexIntoByte); value = (indexedByte >> mod) % 32; } if (indexIntoByte > 3) { uint8 leftoverBits = indexIntoByte - 3; uint8 nextByte = uint8(tokenData[indexIntoBytes + 1]); value += nextByte >> (8 - leftoverBits); } return value; }
415,440
[ 1, 23649, 326, 1381, 17, 3682, 460, 5123, 326, 2036, 770, 364, 279, 864, 4957, 18, 432, 25606, 434, 25337, 5295, 3577, 358, 6892, 333, 3397, 18, 3356, 353, 2195, 9940, 10073, 16, 2537, 10267, 1791, 716, 326, 4233, 6330, 596, 2674, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 15672, 1016, 1265, 9037, 1016, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 4957, 1016, 13, 2713, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 2254, 5034, 770, 5952, 2160, 273, 261, 25, 380, 4957, 1016, 13, 342, 1725, 31, 203, 3639, 2254, 28, 770, 5952, 3216, 273, 2254, 28, 12443, 25, 380, 4957, 1016, 13, 738, 1725, 1769, 203, 203, 3639, 1731, 3778, 1147, 751, 273, 389, 2316, 14305, 63, 2316, 548, 300, 404, 15533, 203, 203, 3639, 2254, 28, 460, 273, 374, 31, 203, 3639, 2254, 28, 8808, 3216, 273, 2254, 28, 12, 2316, 751, 63, 1615, 5952, 2160, 19226, 203, 203, 3639, 309, 261, 1615, 5952, 3216, 1545, 890, 13, 288, 203, 5411, 2254, 28, 681, 273, 2254, 28, 12, 22, 636, 12, 28, 300, 770, 5952, 3216, 10019, 203, 5411, 2254, 28, 4654, 273, 261, 1615, 5952, 3216, 300, 890, 1769, 203, 5411, 460, 273, 261, 19626, 3216, 738, 681, 13, 2296, 4654, 31, 203, 5411, 2254, 28, 681, 273, 261, 23, 300, 770, 5952, 3216, 1769, 203, 5411, 460, 273, 261, 19626, 3216, 1671, 681, 13, 738, 3847, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1615, 5952, 3216, 405, 890, 13, 288, 203, 5411, 2254, 28, 29709, 6495, 273, 770, 5952, 3216, 300, 890, 31, 203, 5411, 2254, 28, 1024, 3216, 273, 2254, 28, 12, 2316, 751, 63, 1615, 5952, 2160, 397, 404, 19226, 203, 203, 5411, 460, 1011, 1024, 3216, 1671, 261, 28, 300, 29709, 6495, 1769, 203, 3639, 289, 203, 203, 3639, 2 ]
./full_match/43114/0xBe7F80d11e5C61194a27C03627102797dd476C71/sources/contracts/CoolFox.sol
* @dev Mint to msg.sender. @param _num addresss of the future owner of the token/
function mint(uint8 _num,address _referalAddress) external payable { require( totalMint + uint256(_num) <= MAX_SUPPLY, "CoolFox: Sorry, all CoolFoxes were sold out." ); require( _num <= 20, "CoolFox: Up to 20 CoolFoxes can be minted in a tx." ); require( "CoolFox: You need to pay the exact price." ); require( msg.value != 0,"You cant pay 0 avax to mint!" ); require( isActive == 1,"The minting process is not active now!" ); _mintList(_num); totalMint += uint256(_num); emit mintSuccessfully(totalMint); }
4,519,080
[ 1, 49, 474, 358, 1234, 18, 15330, 18, 225, 389, 2107, 1758, 87, 434, 326, 3563, 3410, 434, 326, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 11890, 28, 389, 2107, 16, 2867, 389, 266, 586, 287, 1887, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 203, 5411, 2078, 49, 474, 397, 2254, 5034, 24899, 2107, 13, 1648, 4552, 67, 13272, 23893, 16, 203, 5411, 315, 39, 1371, 42, 2409, 30, 348, 21637, 16, 777, 385, 1371, 42, 2409, 281, 4591, 272, 1673, 596, 1199, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 389, 2107, 1648, 4200, 16, 203, 5411, 315, 39, 1371, 42, 2409, 30, 1948, 358, 4200, 385, 1371, 42, 2409, 281, 848, 506, 312, 474, 329, 316, 279, 2229, 1199, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 315, 39, 1371, 42, 2409, 30, 4554, 1608, 358, 8843, 326, 5565, 6205, 1199, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 480, 374, 10837, 6225, 848, 88, 8843, 374, 1712, 651, 358, 312, 474, 4442, 203, 5411, 11272, 203, 3639, 2583, 12, 203, 5411, 15083, 422, 404, 10837, 1986, 312, 474, 310, 1207, 353, 486, 2695, 2037, 4442, 203, 5411, 11272, 203, 3639, 389, 81, 474, 682, 24899, 2107, 1769, 203, 3639, 2078, 49, 474, 1011, 2254, 5034, 24899, 2107, 1769, 203, 3639, 3626, 312, 474, 18303, 12, 4963, 49, 474, 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 ]
pragma solidity >=0.5.0; contract ContractDeployer { // Struct to store information about deployed contracts. struct DeployedContract { address addr; TvmCell stateInit; uint256 pubkey; } // Deployed contracts database. mapping(uint => DeployedContract) contracts; uint public lastID = 0; // Modifier that allows public function to accept external calls only from the contract owner. modifier acceptOnlyOwner { require(tvm.pubkey() == msg.pubkey(), 101); tvm.accept(); _; } // First variant of contract deployment. function deployWithPubkey(TvmCell stateInit, uint256 pubkey, uint128 initial_balance, uint32 constructor_id, uint32 constructor_param0, uint constructor_param1) public acceptOnlyOwner returns (address, uint) { // Runtime function that inserts public key into contracts data field. TvmCell stateInitWithKey = tvm.insertPubkey(stateInit, pubkey); // tvm.hash() - Runtime function that computes the representation hash ot TvmCell. address addr = address(tvm.hash(stateInitWithKey)); // Functions to deploy a contract and call it's constructor. tvm.deployAndCallConstructor(stateInitWithKey, addr, initial_balance, constructor_id, constructor_param0, constructor_param1); uint newID = lastID; contracts[newID] = DeployedContract(addr, stateInitWithKey, pubkey); lastID = newID + 1; return (addr, newID); } // Second variant of contract deployment. function deployFromCodeAndData(TvmCell code, TvmCell data, uint128 initial_balance, uint32 constructor_id, uint32 constructor_param0, uint constructor_param1) public acceptOnlyOwner returns (address, uint) { // Runtime function to generate StateInit from code and data cells. TvmCell stateInit = tvm.buildStateInit(code, data); // tvm.hash() - Runtime function that computes the representation hash ot TvmCell. address addr = address(tvm.hash(stateInit)); // Functions to deploy a contract and call it's constructor. tvm.deployAndCallConstructor(stateInit, addr, initial_balance, constructor_id, constructor_param0, constructor_param1); // In this function we deploy contract without public key, that's why we store struct with zero pubkey. uint newID = lastID; contracts[newID] = DeployedContract(addr, stateInit, 0); lastID = newID + 1; return (addr, newID); } // Third variant of contract deployment. function deployWithMsgBody(TvmCell stateInit, address addr, uint128 initial_balance, TvmCell payload) public acceptOnlyOwner returns (address, uint) { // Runtime function to deploy contract with prepared msg body for constructor call. tvm.deploy(stateInit, addr, initial_balance, payload); uint newID = lastID; contracts[newID] = DeployedContract(addr, stateInit, 0); lastID = newID + 1; return (addr, newID); } // Function that allows to get address of the last deployed contract. function getAddressOfLastDeployedContract() public view acceptOnlyOwner returns (address) { DeployedContract contr = contracts[lastID - 1]; return contr.addr; } // Function that allows to get information about contract with given ID. function getContractInfo(uint ID) public view acceptOnlyOwner returns (bool, address, TvmCell, uint256) { (bool exists, DeployedContract contr) = contracts.fetch(ID); if (exists) return (true, contr.addr, contr.stateInit, contr.pubkey); TvmCell cell; return (false, address(0), cell, 0); } }
Deployed contracts database.
mapping(uint => DeployedContract) contracts;
7,274,117
[ 1, 31954, 20092, 2063, 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, 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, 202, 6770, 12, 11890, 516, 7406, 329, 8924, 13, 20092, 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 ]
pragma solidity ^0.4.24; contract e0x { event LinkVisited(string url, uint linkId); event LinkAdded(uint linkId, string url); struct LinkTemplate { address userAddress; string url; } uint lastLinkId; mapping (uint => LinkTemplate) public linkMapping; constructor() public { lastLinkId = 0; } function createNewLink(string url) public returns (uint) { lastLinkId++; linkMapping[lastLinkId] = LinkTemplate(msg.sender, url); emit LinkAdded(lastLinkId, url); return lastLinkId; } modifier linkExists(uint linkId) { //link with the given hash does not exist if(linkMapping[linkId].userAddress == 0x0000000000000000000000000000000000000000) { revert(); } _; } function getLink(uint linkId) linkExists(linkId) public constant returns( address, string ) { //emit LinkVisited(linkId, link.url); LinkTemplate memory link = linkMapping[linkId]; return( link.userAddress, link.url ); } }
link with the given hash does not exist
modifier linkExists(uint linkId) { if(linkMapping[linkId].userAddress == 0x0000000000000000000000000000000000000000) { revert(); } _; }
2,525,433
[ 1, 1232, 598, 326, 864, 1651, 1552, 486, 1005, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1692, 4002, 12, 11890, 1692, 548, 13, 288, 203, 225, 309, 12, 1232, 3233, 63, 1232, 548, 8009, 1355, 1887, 422, 374, 92, 12648, 12648, 12648, 12648, 12648, 13, 288, 203, 282, 15226, 5621, 203, 225, 289, 203, 225, 389, 31, 203, 289, 203, 7010, 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 ]
./full_match/1/0xE540D1b18B40dF28b844F77C26d5A9b01b966E57/sources/src/SharpFactsAggregator.sol
@notice Returns the current root hash of the Keccak Merkle Mountain Range (MMR) tree
function getMMRKeccakRoot() external view returns (bytes32) { return aggregatorState.keccakMmrRoot; }
16,518,370
[ 1, 1356, 326, 783, 1365, 1651, 434, 326, 1475, 24410, 581, 31827, 13076, 530, 8086, 261, 8206, 54, 13, 2151, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2108, 23464, 47, 24410, 581, 2375, 1435, 3903, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 327, 20762, 1119, 18, 79, 24410, 581, 49, 21387, 2375, 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 ]
// Правила для изменения достоверности распознавания конкретных словоформ в русском словаре. // Обычное предназначение этих правил - изменить равновероятные распознавания // омонимичных форм жаль(безличный глагол)>жаль(императив), // либо повлиять на выбор многословных форм в противовес // выбору отдельных слов: [слева от] <--> [слева] [от] wordform_score смеси{глагол}=-10 // из чего смеси ? wordform_score ага{ существительное }=-5 wordform_score малышки{ род:муж }=-10 // Малышки будут прыгать от радости! wordform_score мебели{ число:мн }=-10 // Рвали обивку мебели. wordform_score начало{ глагол }=-6 // Сегодня неплохое начало. wordform_score воды{ род:муж }=-10 // мы приплывем в их воды wordform_score скалы{ род:муж }=-10 // там должны быть скалы wordform_score кафе{ род:муж }=-10 // в кафе wordform_score скалы{ род:муж }=-10 // волны бились о скалы wordform_score кроме{ существительное }=-10 // кроме этой вот ягоды wordform_score жилище{ род:жен }=-10 // в ее жилище wordform_score почитай{ наречие }=-4 // Ты лучше почитай. wordform_score без{ существительное }=-10 // Без кладовок и гардеробных комнат wordform_score бренды{род:жен}=-10 // Вообще-то перечисленные бренды давно уже избавились от налета местечковости. wordform_score ярки{ существительное }=-10 // Глаза его были ярки wordform_score голубей{ прилагательное }=-1 // Ты будешь Петькиных голубей подманивать. wordform_score дело{ глагол }=-10 // Дело наше лесное. wordform_score правило{ глагол }=-5 // Такое наше правило... wordform_score карусель{ глагол }=-10 // Карусель начинается мировая. wordform_score Германии{ число:мн }=-10 // В Германии беженец спрыгнул с поезда из-за угрозы депортации в Италию wordform_score бусы { род:муж }=-5 // Весенние бусы персикового дерева разорвались. wordform_score суеты { число:мн }=-10 // Завершился 26-ой тур российской премьер-лиги. wordform_score метель { глагол }=-10 // На улице метель. //wordform_score по-видимому { наречие }=2 //wordform_score по-видимому { вводное }=2 // Ему, по-видимому, не терпелось начать. wordform_score энергии { существительное число:мн }=-2 // Ему и сейчас не занимать энергии. wordform_score таки { существительное }=-5 // Ему-таки удалось ее завести. wordform_score выстуживаем { прилагательное }=-1 wordform_score уполномочиваем { прилагательное }=-1 wordform_score кормим { прилагательное }=-1 wordform_score чиним { прилагательное }=-1 wordform_score заводим { прилагательное }=-1 wordform_score периодизируем { прилагательное }=-1 wordform_score завозим { прилагательное }=-1 wordform_score дегустируем { прилагательное }=-1 wordform_score увозим { прилагательное }=-1 wordform_score вообразим { прилагательное }=-1 wordform_score дробим { прилагательное }=-1 wordform_score таскаем { прилагательное }=-1 wordform_score превозносим { прилагательное }=-1 wordform_score потопляем { прилагательное }=-1 wordform_score волочим { прилагательное }=-1 wordform_score перевиваем { прилагательное }=-1 wordform_score засекречиваем { прилагательное }=-1 wordform_score храним { прилагательное }=-1 wordform_score уносим { прилагательное }=-1 wordform_score предводим { прилагательное }=-1 wordform_score мыслим { прилагательное }=-1 wordform_score проходим { прилагательное }=-1 wordform_score влачим { прилагательное }=-1 wordform_score творим { прилагательное }=-1 wordform_score сравним { прилагательное }=-1 wordform_score измерим { прилагательное }=-1 wordform_score душим { прилагательное }=-1 wordform_score сопоставим { прилагательное }=-1 wordform_score досягаем { прилагательное }=-1 wordform_score травим { прилагательное }=-1 wordform_score благоволим { прилагательное }=-1 wordform_score убеждаем { прилагательное }=-1 wordform_score слышим { прилагательное }=-1 wordform_score слышим { прилагательное }=-1 wordform_score подгружаем { прилагательное }=-1 wordform_score укрупняем { прилагательное }=-1 wordform_score взымаем { прилагательное }=-1 wordform_score зашвыриваем { прилагательное }=-1 wordform_score зависим { прилагательное }=-1 wordform_score ощутим { прилагательное }=-1 wordform_score громим { прилагательное }=-1 wordform_score застраиваем { прилагательное }=-1 wordform_score исправим { прилагательное }=-1 wordform_score выполним { прилагательное }=-1 wordform_score производим { прилагательное }=-1 wordform_score втемяшиваем { прилагательное }=-1 wordform_score содержим { прилагательное }=-1 wordform_score подносим { прилагательное }=-1 wordform_score вкраиваем { прилагательное }=-1 wordform_score беспокоим { прилагательное }=-1 wordform_score взнуздываем { прилагательное }=-1 wordform_score носим { прилагательное }=-1 wordform_score любим { прилагательное }=-1 wordform_score доносим { прилагательное }=-1 wordform_score уценяем { прилагательное }=-1 wordform_score ненавидим { прилагательное }=-1 wordform_score судим { прилагательное }=-1 wordform_score вмораживаем { прилагательное }=-1 wordform_score ввозим { прилагательное }=-1 wordform_score подвозим { прилагательное }=-1 wordform_score развозим { прилагательное }=-1 wordform_score привозим { прилагательное }=-1 wordform_score реструктурируем { прилагательное }=-1 wordform_score реструктурируем { прилагательное }=-1 wordform_score подтопляем { прилагательное }=-1 wordform_score перезаписываем { прилагательное }=-1 wordform_score ценим { прилагательное }=-1 wordform_score национализируем { прилагательное }=-1 wordform_score национализируем { прилагательное }=-1 wordform_score проминаем { прилагательное }=-1 wordform_score переносим { прилагательное }=-1 wordform_score возводим { прилагательное }=-1 wordform_score проницаем { прилагательное }=-1 wordform_score проводим { прилагательное }=-1 wordform_score проводим { прилагательное }=-1 wordform_score таим { прилагательное }=-1 wordform_score синхронизируем { прилагательное }=-1 wordform_score вводим { прилагательное }=-1 wordform_score гоним { прилагательное }=-1 wordform_score разделим { прилагательное }=-1 wordform_score ввариваем { прилагательное }=-1 wordform_score бороздим { прилагательное }=-1 wordform_score воспоминаем { прилагательное }=-1 wordform_score руководим { прилагательное }=-1 wordform_score сносим { прилагательное }=-1 wordform_score разносим { прилагательное }=-1 wordform_score стандартизируем { прилагательное }=-1 wordform_score терпим { прилагательное }=-1 wordform_score выносим { прилагательное }=-1 wordform_score выносим { прилагательное }=-1 wordform_score боготворим { прилагательное }=-1 wordform_score клоним { прилагательное }=-1 wordform_score прозываем { прилагательное }=-1 wordform_score привносим { прилагательное }=-1 wordform_score соизмерим { прилагательное }=-1 wordform_score компилируем { прилагательное }=-1 wordform_score централизуем { прилагательное }=-1 wordform_score упаковываем { прилагательное }=-1 wordform_score возбудим { прилагательное }=-1 wordform_score отделим { прилагательное }=-1 wordform_score ограбляем { прилагательное }=-1 wordform_score объясним { прилагательное }=-1 wordform_score наводим { прилагательное }=-1 wordform_score подводим { прилагательное }=-1 wordform_score исполним { прилагательное }=-1 wordform_score вычислим { прилагательное }=-1 wordform_score монетизируем { прилагательное }=-1 wordform_score отряжаем { прилагательное }=-1 wordform_score разъединим { прилагательное }=-1 wordform_score заменим { прилагательное }=-1 wordform_score охаиваем { прилагательное }=-1 wordform_score растворим { прилагательное }=-1 wordform_score наносим { прилагательное }=-1 wordform_score уничтожим { прилагательное }=-1 wordform_score томим { прилагательное }=-1 wordform_score заполним { прилагательное }=-1 wordform_score сводим { прилагательное }=-1 wordform_score выводим { прилагательное }=-1 wordform_score перевозим { прилагательное }=-1 wordform_score взаимозаменяем { прилагательное }=-1 wordform_score поносим { прилагательное }=-1 wordform_score вверстываем { прилагательное }=-1 wordform_score воспроизводим { прилагательное }=-1 wordform_score вывозим { прилагательное }=-1 wordform_score прорежаем { прилагательное }=-1 wordform_score дренируем { прилагательное }=-1 wordform_score разграбляем { прилагательное }=-1 wordform_score обеззараживаем { прилагательное }=-1 wordform_score тесним { прилагательное }=-1 wordform_score вносим { прилагательное }=-1 wordform_score разрешим { прилагательное }=-1 wordform_score подбодряем { прилагательное }=-1 wordform_score уловим { прилагательное }=-1 wordform_score вдергиваем { прилагательное }=-1 wordform_score автопилотируем { прилагательное }=-1 wordform_score автопилотируем { прилагательное }=-1 wordform_score воссоединяем { прилагательное }=-1 wordform_score фондируем { прилагательное }=-1 wordform_score зрим { прилагательное }=-1 wordform_score допустим { прилагательное }=-1 wordform_score преподносим { прилагательное }=-1 wordform_score устраним { прилагательное }=-1 wordform_score устрашим { прилагательное }=-1 wordform_score поправим { прилагательное }=-1 wordform_score нарезаем { прилагательное }=-1 wordform_score значим { прилагательное }=-1 wordform_score истребим { прилагательное }=-1 wordform_score окормляем { прилагательное }=-1 wordform_score воплотим { прилагательное }=-1 wordform_score будоражим { прилагательное }=-1 wordform_score тревожим { прилагательное }=-1 wordform_score применим { прилагательное }=-1 wordform_score дактилоскопируем { прилагательное }=-1 wordform_score дактилоскопируем { прилагательное }=-1 wordform_score браним { прилагательное }=-1 wordform_score провозим { прилагательное }=-1 wordform_score чтим { прилагательное }=-1 wordform_score приложим { прилагательное }=-1 wordform_score повторим { прилагательное }=-1 wordform_score вменяем { прилагательное }=-1 wordform_score раздробляем { прилагательное }=-1 wordform_score льготируем { прилагательное }=-1 wordform_score перезаправляем { прилагательное }=-1 wordform_score удовлетворим { прилагательное }=-1 wordform_score отводим { прилагательное }=-1 wordform_score переводим { прилагательное }=-1 wordform_score утапливаем { прилагательное }=-1 wordform_score предотвратим { прилагательное }=-1 wordform_score тормозим { прилагательное }=-1 wordform_score вербализуем { прилагательное }=-1 wordform_score тостуем { прилагательное }=-1 wordform_score разводим { прилагательное }=-1 wordform_score уводим { прилагательное }=-1 wordform_score искореним { прилагательное }=-1 wordform_score протапливаем { прилагательное }=-1 wordform_score изготавливаем { прилагательное }=-1 wordform_score изъясним { прилагательное }=-1 wordform_score употребим { прилагательное }=-1 wordform_score разложим { прилагательное }=-1 wordform_score возносим { прилагательное }=-1 wordform_score проносим { прилагательное }=-1 wordform_score предвидим { прилагательное }=-1 wordform_score полимеризуем { прилагательное }=-1 wordform_score полимеризуем { прилагательное }=-1 wordform_score исчислим { прилагательное }=-1 wordform_score погрешим { прилагательное }=-1 wordform_score совместим { прилагательное }=-1 wordform_score впериваем { прилагательное }=-1 wordform_score приносим { прилагательное }=-1 wordform_score доводим { прилагательное }=-1 wordform_score заносим { прилагательное }=-1 wordform_score вытаращиваем { прилагательное }=-1 wordform_score обоготворяем { прилагательное }=-1 wordform_score наметаем { прилагательное }=-1 wordform_score делим { прилагательное }=-1 wordform_score хвалим { прилагательное }=-1 wordform_score излечим { прилагательное }=-1 wordform_score обратим { прилагательное }=-1 wordform_score уязвим { прилагательное }=-1 wordform_score определим { прилагательное }=-1 wordform_score произносим { прилагательное }=-1 wordform_score возобновим { прилагательное }=-1 wordform_score соотносим { прилагательное }=-1 wordform_score победим { прилагательное }=-1 wordform_score раним { прилагательное }=-1 wordform_score отличим { прилагательное }=-1 wordform_score прокачиваем { прилагательное }=-1 wordform_score рейтингуем { прилагательное }=-1 wordform_score растравляем { прилагательное }=-1 wordform_score коров { род:муж } = -2 // Без коров мужчины погибли бы. wordform_score ангел { род:жен } = -2 // А мисс Уиллоу была просто ангел. wordform_score слаб { глагол } = -1 // Просто ты слаб! //wordform_score писал { stress:"п^исал" } = -1 // Державин писал: //wordform_score писала { stress:"п^исала" } = -1 wordform_score сердит { глагол } = -1 // Он очень сердит. wordform_score ребят { падеж:зват } = -1 // Ребят пора вернуть wordform_score помочь { существительное } = -10 // мы хотим вам помочь wordform_score вон { существительное } = -1 // Я вон зарабатываю. wordform_score скалами { род:муж } = -5 // Миновав Море Акул, путешественники оказались над Крабьими Скалами. wordform_score воды { род:муж } = -5 // выпить воды wordform_score воде { род:муж } = -5 // рожать в воде wordform_score лук { род:жен } = -5 // возьми с собой лук wordform_score базе { род:муж } = -5 // заправлять на базе wordform_score порошки { род:жен } = -5 // Порошки не помогают... wordform_score обезвреживания { число:мн } = -5 // Разработали план обезвреживания. wordform_score трех { существительное } = -10 // Считаю до трех. wordform_score метель { глагол } = -10 // На улице метель. wordforms_score городской { существительное }=-1 // Существуют городские правила, касающиеся этих процедур. wordforms_score утесать {глагол}=-5 // Я утешу тебя. wordforms_score примереть {глагол}=-5 // Внутри пример wordforms_score запоить {глагол}=-5 // Я запою wordforms_score новое { существительное }=-5 // Начинаются поиски новых приемов, новых методов. wordforms_score просек { существительное }=-5 // Матросы переползали просеку. wordforms_score прививок { существительное }=-10 wordforms_score полок { существительное род:муж }=-5 // Началась переправа полков. wordforms_score уток { существительное род:муж }=-10 wordforms_score юр { существительное }=-10 wordforms_score наркотика { существительное род:жен }=-10 // Одно время она даже пыталась бросить наркотики wordforms_score полян { существительное род:муж }=-10 wordforms_score полянин { существительное род:муж }=-10 wordforms_score чужой { существительное }=-5 // голос ее стал чужим wordforms_score живой { существительное }=-5 // но оно было живым! wordforms_score пяток { существительное }=-5 // сверкать пятками wordforms_score ложок { существительное }=-5 // звякнуть ложками wordforms_score костра { существительное }=-5 // сжечь на костре wordforms_score роить { глагол }=-10 // Я рою траншеи wordforms_score ситце { род:ср }=-10 // шить из ситца wordforms_score взяток { существительное }=-10 // Врач попался на взятке wordforms_score сило { существительное }=-10 // Оставить в силе закон. wordforms_score покадить { глагол }=-5 // Я после покажу... wordforms_score выло { существительное }=-5 // Як не выл больше. wordforms_score вылезть { глагол }=-1 // Я медленно вылез. wordforms_score лунь { существительное }=-1 // Астронавты смогут оставаться на Луне в течение недели wordforms_score закроить { глагол }=-1 // Я потом закрою. wordforms_score вылезть { глагол }=-1 // Машинист вылез. wordforms_score охаять { глагол }=-1 // Кто охает? wordforms_score покадить { глагол }=-1 // Я покажу! wordforms_score ила { существительное род:жен }=-5 // Я раскопал ил wordforms_score ос { существительное род:муж }=-5 // В воздухе гудели мухи и осы. wordforms_score прикроить { глагол }=-2 // Атакуй, прикрою. wordforms_score ох { существительное }=-2 // Ей это ох как не нравилось. wordforms_score кровяный { прилагательное }=-2 // Стимулирует кровообращение и снижает кровяное давление. wordforms_score жило { существительное }=-5 // Именно так выглядит обычный кварц рудных жил. wordforms_score крон { существительное } =-5 // Видите эти могучие кроны, тяжелые плоды? wordforms_score утюжка { существительное }=-5 wordforms_score нар { существительное }=-2 wordforms_score подбора { существительное }=-10 wordforms_score кормило { существительное }=-10 wordforms_score дубка { существительное }=-2 // Сам горб порос крепкими дубками. wordforms_score кода { существительное }=-5 // Серые ячейки указывают на неназначенные коды wordforms_score песнь { существительное }=-1 // Проводится круглогодичный конкурс бардовской песни. wordforms_score тоника { существительное }=-10 wordforms_score рака { существительное }=-10 wordforms_score бахчевый { прилагательное }=-5 // Особое внимание уделялось бахчевым культурам. wordforms_score нецелевый { прилагательное }=-5 // Процветало нецелевое использование этих средств. wordforms_score запасный { прилагательное }=-5 // Пятигорский вокзал был запасным вариантом. wordforms_score бредовой { прилагательное }=-5 // Первая стопка содержала бредовые работы. wordforms_score меньшой { прилагательное }=-5 // Такие передачи имеют меньшую аудиторию. wordforms_score меховый { прилагательное }=-5 // Летняя распродажа меховых изделий продолжается! wordforms_score заводский { прилагательное }=-10 // Существует заводская группа внутренних аудиторов. wordforms_score щенка { существительное }=-10 // Продаются красивые щенки йоркширского терьера. wordforms_score кур { существительное }=-10 wordforms_score любый { прилагательное }=-10 // Для него любая власть является раздражителем. wordforms_score ванный { прилагательное }=-1 // большая ванная wordforms_score плавной { прилагательное }=-10 // Такая конструкция обеспечивает плавное перемещение wordforms_score санатория { существительное }=-10 wordforms_score шпалер { существительное }=-10 wordforms_score хромый { прилагательное }=-5 // Волшебный лепесток излечивает хромого мальчика. wordforms_score газа { существительное }=-1 // Раскаленные газы с чудовищной силой вырываются wordforms_score рейки { род:ср }=-10 // Многочисленные рейки стягивала стальная проволока. wordforms_score протяжной { прилагательное }=-5 // Каменные своды отозвались протяжным эхом. wordforms_score страстной { прилагательное }=-2 // Страстная любовь вызывает страстную борьбу. wordforms_score дневный { прилагательное }=-2 // Дневная суета сменилась полной тишиной. wordforms_score хромый { прилагательное }=-2 // Гони эту свору хромого горбуна! wordforms_score восковой { прилагательное }=-5 // Восковые свечи разливали мягкое сияние. wordforms_score угловый { прилагательное }=-5 // Угловая камера записала этот момент. wordforms_score пестрить { глагол }=-10 // Мировая пресса пестрит сенсационными сообщениями. wordforms_score чина { существительное }=-5 // Это требование поддержали высшие чины. wordforms_score языковый { прилагательное }=-5 wordforms_score половый { прилагательное }=-5 // Переполненный желудок затрудняет половой акт. wordforms_score шампанский { прилагательное }=-5 wordforms_score замок { глагол }=-10 // Замок небольшой и необычный. wordforms_score синоптика { существительное }=-5 // Русский сухогруз утопили турецкие синоптики. wordforms_score корректив { существительное род:муж }=-10 // Президентские выборы вносят определенные коррективы. wordforms_score поджога { существительное род:жен }=-10 // Умышленные поджоги стали доходным бизнесом. wordforms_score матерь { существительное }=-1 wordforms_score плюсовый { прилагательное }=-1 wordforms_score экой { прилагательное }=-1 // Экую несуразицу плетет этот мужик. wordforms_score овсяной { прилагательное }=-5 // Сморщенный чиновник жует овсяную лепешку. wordforms_score хмельный { прилагательное }=-1 // Остался ровный шелест хмельных кипарисов. wordforms_score спазма { существительное }=-10 // Пустой желудок разрывали болезненные спазмы. wordforms_score мазка { существительное }=-10 // Замельтешили нервные мазки ярких красок... wordforms_score громовый { прилагательное }=-5 // Эти вспышки сопровождались громовыми ударами. wordforms_score зарев { существительное }=-10 // Длинные пальцы налились красноватым заревом. wordforms_score шара { существительное }=-5 // Латунные шары заполнялись керосиновой смесью. wordforms_score корн { существительное }=-5 // в корне мандрагоры содержится наркотический сок wordforms_score справа { существительное }=-10 // Справа Дэни разглядела маленькое каменное святилище. wordforms_score теля { существительное }=-5 // Было чувство клаустрофобии в собственном теле. wordforms_score коленной { прилагательное }=-5 // 26-летний футболист получил растяжение коленного сустава. wordforms_score полом { существительное }=-5 // Бойцы рыли под полом окопы. wordforms_score бород { существительное }=-5 // Елена просит молодого мужа сбрить бороду. wordform_score присутствия { число:мн }=-5 // // Ей стало не хватать его присутствия. wordform_score косы { род:муж число:мн }=-10 // Ее косы были убраны под шапку. wordform_score обожания { число:мн }=-10 // Изливают любвеобильные лучи обожания wordform_score смелости { число:мн }=-10 // Ей просто недоставало смелости его сделать. wordform_score ясности { число:мн }=-10 // Черные ящики не добавили ясности. wordform_score с { частица }=-2 // // Загадали желания – ждем-с! wordform_score "ей-богу"{} = 10 // Ей-богу, отлично выйдет. wordform_score дыхания { число:мн }=-2 // Ее подключили к аппарату искусственного дыхания. wordform_score реставрации { число:мн }=-2 // Ее не ремонтировали со времен Реставрации. wordform_score бересты { число:мн }=-10 // Сверху настелили большие куски бересты. wordform_score охоты { число:мн }=-10 // Сезон охоты откроют 25 августа. wordform_score развития { существительное число:мн }=-10 // В Чувашии обсуждают проблемы инновационного развития регионов wordform_score наглости { существительное число:мн }=-10 // противопоставить наглости wordform_score еды { существительное число:мн }=-5 // хозяин должен дать еды wordform_score безопасности { существительное число:мн }=-5 // Его обвинили в пренебрежении вопросами безопасности. wordform_score выдержки { существительное число:мн }=-5 // Если хватит выдержки... wordform_score истерик { существительное }=-2 // И хватит истерик! wordform_score послезавтра { существительное }=-5 // Послезавтра утром проверю... wordform_score дискриминации { число:мн }=-5 // Его называли анахронизмом и признаком дискриминации. wordform_score полиции { число:мн }=-5 // Его доставили в 20-й отдел полиции. wordform_score уверенности { число:мн }=-10 // Его немое обожание придавало Анне уверенности. wordform_score насилия { число:мн }=-5 // А насилия Рекс никогда не совершит. wordform_score болтовни { число:мн }=-10 // А теперь хватит болтовни, Кейн. wordform_score оружия { число:мн }=-10 // А Филип вообще не любит оружия. wordform_score внимания { число:мн }=-10 // А на брата не обращай внимания. wordform_score бытия { число:мн }=-10 // Имеют телесную форму предшествовавшего бытия. wordform_score сочувствия { число:мн }=-5 // А вот Мария действительно заслуживает сочувствия. wordform_score разнообразия { число:мн }=-5 // Болото хотело разнообразия в компании. wordform_score ним { существительное }=-5 // А вместе с ним и свою душу. wordform_score ник { глагол }=-5 // А ты как думаешь, Ник? wordform_score тете { одуш:неодуш }=-1 // А перед этим послал тете цветы. wordform_score гораздо { прилагательное }=-5 // А кажется, что гораздо больше. wordform_score Калифорнии { число:мн }=-10 // А в Калифорнии сейчас цветет мимоза. wordform_score замок { глагол }=-10 // А на краю леса красивый замок. wordform_score мирке { род:жен }=-5 // В их мирке вдруг оказался третий. wordform_score жалости { число:мн }=-5 // В этом деле не знают жалости. wordform_score орала { существительное }=-5 // Я била подушки и орала в ярости. wordform_score яркости { число:мн }=-2 // Второй цвет добавляет яркости и выразительности. wordform_score выразительности { число:мн }=-10 // Второй цвет добавляет яркости и выразительности. wordform_score македонии { число:мн }=-10 // Встретились главы МИД России и Македонии. wordform_score бочками { род:муж }=-5 // Грузить апельсины бочками? wordform_score полдня { существительное }=-5 // Полдня шел дождь. wordform_score пол { падеж:род }=-5 // Меряю шагами пол. wordform_score правей { глагол }=-10 // Еще чуть правей... wordform_score чуточку { существительное }=-10 // Самолет чуточку подбросило. wordform_score правосудья { число:мн }=-10 // Жид хочет правосудья wordform_score единства { число:мн }=-10 // Партия хочет единства. wordform_score счастья { число:мн }=-10 // Все хотят счастья. wordform_score агрессии { число:мн }=-10 // Фашизм хочет агрессии?.. wordform_score горючки { число:мн }=-10 // Не хватило горючки. wordform_score усмирения { число:мн }=-10 // Потребовать усмирения Петрограда. wordform_score метель { глагол }=-15 // На улице метель. wordform_score ясней { глагол }=-10 // Куда уж ясней. wordform_score штурману { глагол }=-10 // Штурману тоже трудно. wordform_score целиком { существительное }=-10 // Скука съела целиком. wordform_score хмелю { глагол }=-10 wordform_score четкой { существительное }=-2 // Работа персонала была четкой wordform_score милую { глагол }=-10 wordform_score гордости { число:мн }=-10 // Есть другие предметы, достойные гордости. wordform_score тих { глагол }=-10 wordform_score инфраструктуры { число:мн }=-2 // РАЗРАБОТАЮТ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ЭЛЕКТРОННОЙ ИНФРАСТРУКТУРЫ. wordform_score ангелы { род:жен }=-5 wordform_score большие { СТЕПЕНЬ:СРАВН }=-10 // большие отели wordform_score больших { СТЕПЕНЬ:СРАВН }=-10 wordform_score большим { СТЕПЕНЬ:СРАВН }=-10 wordform_score большими { СТЕПЕНЬ:СРАВН }=-10 wordform_score физики { род:жен } =-5 // Волгоградские Физики совершили научную революцию. wordform_score хорошей { глагол }=-10 // хорошей душевой кабиной wordform_score стиле { существительное род:ср }=-2 // Продам свадебное платье в греческом стиле wordform_score молока { род:жен падеж:им }=-2 wordform_score Турции { число:мн }=-5 // В Турции муллы провозглашают священную войну. wordform_score гости { глагол }=-5 // В саду могут оказаться и гости. wordform_score администрации { число:мн }=-5 // Структуру администрации Краснодара изменят wordform_score горячим { глагол }=-5 wordform_score свежую { глагол }=-5 // свежую рыбу wordform_score голубой { существительное }=-10 // за дверью жил голубой лев wordform_score фанту { род:муж }=-5 wordform_score фанте { род:муж }=-5 wordform_score баню { ГЛАГОЛ }=-5 wordform_score бань { ГЛАГОЛ }=-5 wordform_score сласти { ГЛАГОЛ }=-10 wordform_score сыр { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score сыра { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score сыры { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score альбом { ПАДЕЖ:ТВОР }=-5 // По запросу могу показать альбом. wordform_score хоре { падеж:предл одуш:одуш }=-5 // подпевать в церковном хоре wordform_score Европы { число:мн }=-5 // Ее считали прекраснейшей женщиной Европы. wordform_score свежую { глагол }=-6 // свежую форель wordform_score содействия { число:мн }=-5 wordform_score общества { число:мн }=-1 // Индивидуальную честность связали с прогрессивностью общества wordform_score подготовки { число:мн }=-5 // Процесс подготовки спутника к запуску уместили в короткий видеоролик wordform_score недвижимости { число:мн }=-10 // Тест: способны ли вы отличить рекламу недвижимости от рекламы презервативов? wordform_score родины { число:мн }=-2 // Кандидата «Родины» уличили в получении поддельного военного билета wordform_score защиты { число:мн }=-2 // Google просит защиты у Аркадия Дворковича wordform_score освобождения { число:мн }=-5 // В Болгарии отпраздновали годовщину освобождения от османского ига wordform_score веры { число:мн }=-5 // Папу Римского призвали отказаться от догмата своей непогрешимости в вопросах веры wordforms_score гнома { существительное }=-10 // Но гномы начали погоню wordform_score рада { существительное }=-2 wordform_score полон { существительное }=-10 // а этот полон ненависти wordform_score Марин { существительное }=-2 // Алла отпустила Марину wordforms_score снимка { существительное }=-5 wordforms_score ям { существительное }=-5 wordforms_score купа { существительное }=-5 // мы нашли в его купе wordforms_score половый { прилагательное }=-5 wordforms_score теста { существительное }=-5 // выявляться тестами wordforms_score гриба { существительное }=-5 // отравиться грибами wordforms_score босый { прилагательное }=-5 // ноги ее были босые wordforms_score арен { существительное }=-5 wordforms_score плат { существительное }=-5 wordforms_score теста { существительное род:жен }=-5 wordforms_score бара { существительное род:жен }=1 // праздновать в баре wordform_score погиб { существительное }=-5 wordforms_score хора { существительное }=-5 wordforms_score дворовой { прилагательное }=-5 wordforms_score сводной { прилагательное }=-5 wordforms_score шпор { существительное }=-5 wordform_score сдачи { число:мн }=-2 // Сдачи не надо. wordforms_score комара { существительное }=-5 wordforms_score бара { существительное }=-5 wordforms_score теста { существительное }=-5 wordforms_score венка { существительное }=-5 wordforms_score метода { существительное }=-5 wordforms_score мор { существительное }=-5 wordforms_score мора { существительное }=-5 // Море достаточно холодное wordform_score трое { существительное }=-5 // трое из мира людей wordform_score повезло { глагол }=-2 // - Не повезло тебе. wordforms_score распоряженье { существительное }=-5 // Полицейские стали ждать дальнейших распоряжений. wordforms_score варианта { существительное род:жен }=-10 // Для разных ситуаций есть предпочтительные варианты. wordforms_score лангуста { существительное }=-10 // В рыбном купила огромного сырокопченого лангуста. wordforms_score верховый { прилагательное }=-5 // Бывало, возьмут верховых лошадей и уедут в поле. wordforms_score об { существительное }=-10 wordforms_score слушанье { существительное }=-5 // Регламент проведения публичных слушаний утверждается постановлением городского парламента. wordforms_score леса { существительное }=-5 // В алтайских лесах истребили сибирского коконопряда, объедающего хвою wordforms_score рельса { существительное }=-1 // В основном были подорваны рельсы на второстепенных запасных путях. wordforms_score перекрытье { существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными. wordforms_score бракосочетанье { существительное }=-5 // Но в понедельник во Дворце бракосочетания был выходной. wordforms_score благополучье { существительное } =-5 // В полном благополучии путешественники достигли Вефиля. wordforms_score лет { род:муж }=-5 // Летом в этой бухте собиралась целая флотилия яхт. wordforms_score снов { существительное }=-10 wordforms_score така { существительное }=-5 // Сигнал бедствия от лыжницы так и не поступил. wordforms_score корпусный { прилагательное }=-5 // Снаряд выпустила наша батарея 5-го корпусного артиллерийского полка. wordforms_score окружный { прилагательное }=-5 // В Агинском округе началась внеочередная сессия окружной думы. wordforms_score входный { прилагательное }=-5 // Для делегатов напечатали специальные входные билеты. wordforms_score образной { прилагательное }=-5 // Образное выражение, однако, отражает реальную жизнь. wordforms_score окружный { прилагательное }=-5 // Финансирование осуществлялось из окружного бюджета. wordforms_score дверный { прилагательное }=-5 wordforms_score личной{ прилагательное }=-5 // - А ты пробовал концентрировать свои личные мысли? wordforms_score основный{ прилагательное }=-5 // Основные "боевые" мероприятия проходят в Самаре. wordforms_score мирной{ прилагательное }=-5 // Уже в мирное время миссии тачали хорошие сапоги; wordforms_score ЧЕСТНОЙ{ прилагательное }=-5 // Это было хорошее, честное, благородное желание. wordforms_score РОДНЫЙ{ прилагательное }=-5 // Израильские танкисты приняли меня как родного. wordforms_score назначенье{ существительное }=-5 // В администрации Алтайского края произошел ряд отставок и назначений wordforms_score кадра{ существительное }=-5 wordforms_score перекрытье{ существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными. wordforms_score увечье{ существительное }=-5 // Жертва аварии скончалась в больнице от полученных увечий. wordforms_score исключенье{ существительное }=-5 // Однако из этого правила существует несколько исключений. wordforms_score подкрепленье{ существительное }=-5 // При этом используется вероятностная схема подкреплений. wordforms_score нет{ существительное }=-5 // решение жениться или нет можешь принять только ты сам. wordforms_score признанье{ существительное }=-5 // wordforms_score втора{ существительное }=-5 wordforms_score настроенье{ существительное }=-5 // Но антироссийских настроений вы в Грузии не найдете. wordforms_score заседанье{ существительное }=-5 // Семеро акционеров не были допущены в зал заседаний. wordforms_score сбора{ существительное }=-5 // В ближайшее время Денис улетает на очередные сборы. wordforms_score предложенье{ существительное }=-5 // Вячеслав Евгеньевич готовит свой пакет предложений. wordforms_score свитка{ существительное }=-5 // В кумранских свитках нередко встречается тайнопись wordforms_score носка{ существительное }=-5 // Из-под подола выглядывали белые спортивные носки. wordforms_score дыханье{ существительное }=-5 // При виде обнажившихся грудей перехватило дыхание. wordforms_score усилье{ существительное }=-5 // Бесконечная борьба требовала беспрестанных усилий. wordforms_score помещенье{ существительное }=-5 // Для обработки помещений ядами привлекают бомжей. wordforms_score до{ существительное }=-5 // Санкционированная акция прошла с 16 до 17 часов. wordforms_score ПАРКА{ существительное }=-5 // Королевские парки занимали обширную территорию. wordforms_score НИМ{ существительное }=-5 // Василий, не отрываясь, следит за ним взглядом. wordforms_score СТОЛА{ существительное }=-5 // На столе могут вырастать лужайки зеленой пищи. wordforms_score низка { существительное }=-5 wordforms_score мешка{ существительное }=-5 // Мешки с углем один за другим полетели в темную воду. wordforms_score стен { существительное }=-5 // По стенам развеваются блестящие знамена света. wordforms_score ряда { существительное }=-5 wordforms_score так { существительное }=-5 wordforms_score снова { существительное }=-5 wordforms_score лагер { существительное }=-5 wordforms_score гор { существительное }=-5 wordforms_score карт { существительное }=-5 // Военные топографы и геодезисты сверяют карты. wordforms_score зала { существительное }=-5 wordforms_score зало { существительное }=-5 wordforms_score миро { существительное }=-5 // В макротеле Мира отпечатывается мировая душа. wordforms_score мира { существительное }=-5 wordforms_score облак { существительное }=-5 // По ночным облакам зарумянилось дымное зарево. wordforms_score троп { существительное }=-5 // По берегу идут нерегулярные туристские тропы. wordforms_score пещер { существительное }=-5 wordforms_score ко{ существительное }=-10 // Разумеется, ко мне он больше не показывался. wordforms_score суда{ существительное }=-5 // В ближайшее время начнется его рассмотрение в суде. wordform_score "то и дело" { наречие }=5 // Во всяком случае, не придется то и дело нагибаться. wordform_score "воды" { число:мн } =-1 // они дали ему воды wordform_score "лицо" { одуш:одуш } =-1 wordform_score "лица" { одуш:одуш } =-1 // Ему даже делают специальный массаж лица. wordform_score "лицу" { одуш:одуш } =-1 wordform_score "лице" { одуш:одуш } =-1 wordform_score "лицом" { одуш:одуш } =-1 wordform_score "замок" { глагол } =-5 // замок на горе wordform_score "самогонки" { число:мн } = -1 // Пришлось добавить самогонки. wordform_score "интуиции" { число:мн } = -1 // Больше доверяют интуиции. wordform_score "воды" { число:мн } = -1 // Джек добавил воды. wordform_score "во" { вводное } = -2 // В детях эта программа усиливается во много раз. wordform_score "на" { глагол } =-1 // В эфир выходили на несколько секунд. wordform_score "веселей" { глагол } = -8 // В колонне веселей. wordform_score "гранит" { глагол } = -3 // Почем гранит науки? wordform_score "катя" { деепричастие } = -2 // Катя, давай! wordform_score "прочь" { глагол } = -5 // пойти прочь wordform_score "сволочь" { глагол } = -5 // - Сволочь! wordform_score "юля" { деепричастие } = -2 // Юля, уважь человека. wordform_score "катя" { деепричастие } = -2 // я направляюсь сюда, Катя. wordform_score "женя" { деепричастие } = -2 // Я больше не буду, Женя. wordform_score "нашей" { глагол } = -3 // - А вот и первые плоды нашей работы! wordform_score "Камчатки" { число:мн } = -2 // К аварийной подстанции в столице Камчатки подключают новый трансформатор wordform_score "воротам" { род:муж } = -2 // Беседуя, они подошли к воротам. wordform_score "один" { существительное } = -5 // Значит, он не один. wordform_score "то-то" { частица } = 2 // То-то выслуживается, вас гоняет. wordform_score "погреб" { глагол } =-2 // А вот погреб... wordform_score "просим" { прилагательное } = -5 // Просим всей группой. wordform_score "крови" { число:мн } = -5 // Скорее разойдитесь, не проливая крови! wordform_score "скоро" { прилагательное } = -4 // Скоро в строй? wordform_score "подъем" { глагол } = -5 // Подъем, товарищ майор! wordform_score "порой" { глагол } = -5 // И порой не без успеха. wordform_score "порой" { существительное } = -1 // Они ворчат порой. wordform_score "погоды" { число:мн } = -3 // По случаю чудной погоды Алексея тоже вывозили кататься. wordform_score "дарим" { прилагательное} = -5 // - Решено, дарим один ящик командиру полка! wordform_score "хватит" { глагол } = -1 // - На одну атаку хватит. wordform_score "как ни в чем не бывало" { наречие } = 1 // Ординарец в сенях спал как ни в чем не бывало. wordform_score "разве что" { наречие } = 1 // Так жарко бывает разве что перед грозой. wordform_score "потому что" { союз } =5 // - Потому что мне так нравится. wordform_score "на поводу у"{ предлог} = 1 // Нельзя идти на поводу у таких состояний wordform_score "что" { наречие } = -8 wordform_score "так что" { наречие } = -5 // Ну, так что вы скажете? wordform_score "вот" { наречие } = -3 wordform_score "Иду" { существительное } = -3 // - Иду к тебе! wordform_score "хотите" { НАКЛОНЕНИЕ:ПОБУД } = -5 wordform_score "всего" { наречие } = -4 // Он всего боялся wordform_score "всего лишь" { наречие } = 2 wordform_score "еле-еле" { наречие } = 2 wordform_score "туда-сюда" { наречие } = 2 wordform_score "туда-то" { наречие } = 2 wordform_score "отчего-то" { наречие } = 2 wordform_score "когда-то" { наречие } = 2 wordform_score "чуть-чуть" { наречие } = 2 wordform_score "так-то" { наречие } = 2 wordform_score "наконец-то" { наречие } = 2 wordform_score "туда-то" { наречие } = 2 wordform_score "тут-то" { наречие } = 2 wordform_score "Наконец-то" { наречие } = 2 wordform_score "добро" { наречие } = -4 // - Знаю я это добро. wordform_score "должно" { наречие } = -5 // Но так и должно быть. wordform_score "тем не менее" { наречие } = 1 wordform_score "прежде всего" { наречие } = 1 // Нужно прежде всего знать группу крови. wordform_score "выходит" { наречие } = -2 // это из тебя страх так выходит wordform_score "трибуны" { одуш:одуш } = -2 // Трибуны взрываются аплодисментами. wordform_score "по прошествии" { предлог } = 5 // По прошествии двух дней следствие не может установить их личности. wordform_score "сроком на" { предлог } = 2 // Аэропорт перешел в управление компании сроком на 30 лет. // Я ничего подобного не видал wordform_score "ничего" { наречие } = -5 // Не было таких прецедентов пока что. // ^^^^^^^^ wordform_score "пока что" { наречие } = 1 wordform_score "приводим" { прилагательное } = -5 // Приводим полный текст этого заявления. // Она поколебалась, прежде чем ответить. // ^^^^^^^^^^ wordform_score "прежде чем" { союз } = 1 wordform_score "а то" { союз } = 1 // А то тебе плохо станет. wordform_score "не то" { союз } = 1 // Вставай, не то опоздаем wordform_score "а не то" { союз } = 1 // Сядь, а не то упадешь // кости у всех одинаковые // ^^^^^ wordform_score "кости" { глагол } = -3 wordform_score "чести" { глагол } = -3 // Мы знаем друг друга много лет // ^^^^^^^^^^ wordform_score "друг друга" { существительное падеж:парт } = -1 // Текст речи премьер-министра // ^^^^^^^^^^^^^^^^ wordform_score "премьер-министр" { существительное } = 1 wordform_score "премьер-министра" { существительное } = 1 wordform_score "премьер-министром" { существительное } = 1 wordform_score "премьер-министру" { существительное } = 1 wordform_score "премьер-министре" { существительное } = 1 wordform_score "премьер-министры" { существительное } = 1 wordform_score "премьер-министров" { существительное } = 1 wordform_score "премьер-министрами" { существительное } = 1 wordform_score "премьер-министрам" { существительное } = 1 wordform_score "премьер-министрах" { существительное } = 1 // Хотим получить максимум информации // ^^^^^^^^^^ wordform_score "информации" { существительное число:мн } = -5 wordform_score "тому назад" { послелог } = 1 // Он просто вынужден закончить цикл историй, так как ограничены размеры книги. wordform_score "так как" { союз } = 5 // Поможем ему сена накосить // ^^^^ wordform_score "сена" { существительное число:мн } = -5 // Подавляем множественное число "ПУШОК": // "Мы видели их пушки" wordform_score "пушки" { существительное род:муж } = -5 wordform_score "это" { частица } = -2 // Кажется, вчера еще бродил я в этих рощах. wordform_score "кажется" { наречие } = -2 wordform_score "лицом к лицу" { наречие } = 5 // из конюшни они возвращались бок о бок. wordform_score "бок о бок" { наречие } = 2 // люди спят тем более. wordform_score "тем более" { наречие } = 2 wordform_score "в связи с" { предлог } = 1 // то есть могла бы wordform_score "то есть" { союз } = 3 // ПОКАДИТЬ(ПОКАЖУ) // wordform_score "покажу" { глагол глагол:покадить{} } = -5 // ПРОПАСТЬ>ПРОПАЛИТЬ(ПРОПАЛИ) wordform_score "пропали" { глагол наклонение:побуд } = -5 // ПОПАСТЬ > ПОПАЛИТЬ wordform_score "попали" { глагол наклонение:побуд } = -5 // предпочитаем вариант безличного глагола: //wordform_score "оставалось" { глагол } = -2 //wordform_score "остается" { глагол } = -2 //wordform_score "останется" { глагол } = -2 //wordform_score "осталось" { глагол } = -2 wordform_score "стали" { существительное число:мн } = -5 wordform_score "стали" { существительное падеж:род } = -3 // Жаль, если принятые обязательства не выполняются // ^^^^ wordform_score "жаль" { глагол } = -3 wordform_score "давным-давно" { наречие } = 2 // Можно ли сейчас применять старые методы? wordform_score "методам" { существительное род:жен } = -5 wordform_score "методах" { существительное род:жен } = -5 wordform_score "методу" { существительное род:жен } = -5 wordform_score "методе" { существительное род:жен } = -5 wordform_score "метода" { существительное род:жен } = -5 wordform_score "методы" { существительное род:жен } = -5 // Не вижу необходимости // ^^^^^^^^^^^^^ wordform_score "необходимости" { число:мн } = -1 wordform_score "о" { частица } = -2 wordform_score "Спешите" { наклонение:побуд } = -1 // отдадим преимущество безличной форме: // мне удалось поспать // ^^^^^^^ wordform_score "удалось" { глагол } = -3 // Придавим вариант "ПАР^ОК" // В парке был бассейн с золотыми рыбками. // ^^^^^ wordform_score "парке" { ПЕРЕЧИСЛИМОСТЬ:НЕТ } = -10 // слово БЫЛО редко выступает в роли наречия, но иногда бывает: // один из воинов пошел было к дверям // ^^^^ wordform_score "было" { наречие } = -10 // Это было примерно месяц назад wordform_score "примерно" { прилагательное } = -2 // чтобы подавить ВРЯД(ЛИ) wordform_score "вряд ли" { наречие } = 2 // при помощи женской страсти? // ^^^^^^^^^^ wordform_score "при помощи" { предлог } = 5 wordform_score "Владимиру" { существительное род:жен } = -2 wordform_score "Владимира" { существительное род:жен } = -2 wordform_score "Владимире" { существительное род:жен } = -2 // у тебя впереди серьезное дело wordform_score "дело" { глагол } = -5 wordform_score "правды" { существительное число:мн } = -2 // ты сволочь wordform_score "сволочь" { глагол } = -2 // во мне все же росло беспокойство wordform_score "росло" { прилагательное } = -1 // конкуренция между ЗАБРАТЬ.гл и ЗАБРАЛО.сущ wordform_score "забрала" { существительное } = -2 wordform_score "забрало" { существительное } = -2 wordform_score "забрал" { существительное } = -2 // обычно ЗАВТРА - наречие: // можно зайти за этим завтра? // ^^^^^^ wordform_score "завтра" { существительное } = -10 wordform_score "сегодня" { существительное } = -15 // взять деньги wordform_score "деньги" { существительное падеж:род } = -10 // Подавляем просторечный вариант "Сашок" // Сашка не знал wordform_score "Сашка" { существительное падеж:вин } = -1 wordform_score "Сашка" { существительное падеж:род } = -1 // обычно это - прилагательное wordform_score "простой" { глагол } = -1 // есть варианты ТУШЬ и ТУША (помимо глагола ТУШИТЬ). Вариант ТУШЬ гасим. wordform_score "тушь" { существительное одуш:неодуш } = -5 // обычно ПОЧТИ - это наречие // Почти совсем темно. // ^^^^^ wordform_score "почти" { глагол } = -5 // теперь самое время бросить кости wordform_score "кости" { глагол } = -5 wordform_score "брехло" { наречие } = -10 wordform_score "силой" { наречие } = -2 wordform_score "может" { вводное } = -1 // скорее доедай wordform_score "скорее" { вводное } = -1 wordform_score "пять" { глагол } = -5 wordform_score "спины" { существительное род:муж } = -1 wordform_score "спинах" { существительное род:муж } = -1 wordform_score "спине" { существительное род:муж } = -1 // хозяин дает корм псам wordform_score "корм" { существительное род:жен падеж:род } = -5 // несмотря на жару, солдаты носили шлемы и кирасы. wordform_score "несмотря на" { предлог } = 10 // В соответствии с шариатом, свинину употреблять запрещено // ^^^^^^^^^^^^^^^^ wordform_score "В соответствии с" { предлог } = 2 wordform_score "В соответствии со" { предлог } = 2 // В Дамаске в ходе ракетного обстрела погиб чиновник Евросоюза // ^^^^^^ wordform_score "в ходе" { предлог } = 2 // Мы пошли вместе по направлению к городу. // ^^^^^^^^^^^^^^^^ wordform_score "по направлению к" { предлог } = 2 wordform_score "по направлению ко" { предлог } = 2 // шеф просит еще раз проверить // wordform_score "еще раз" { наречие } = 10 // очень трудно найти задачу по силам wordform_score "по силам" { безлич_глагол } = -1 // есть все же средства // ^^^^^^ wordform_score "все же" { наречие } = 10 // все время находился в командировках // ^^^^^^^^^ //wordform_score "все время" { наречие } = 2 // Однако эти средства до сих пор не дошли до реального сектора экономики wordform_score "до сих пор" { наречие } = 10 // сбыться на самом деле wordform_score "на самом деле" { наречие } = 10 // Лошадь встала на дыбы. wordform_score "встать на дыбы" { инфинитив } = 2 wordform_score "встала на дыбы" { глагол } = 2 wordform_score "встал на дыбы" { глагол } = 2 wordform_score "встали на дыбы" { глагол } = 2 wordform_score "встанет на дыбы" { глагол } = 2 wordform_score "пузырь" { глагол } = -2 // выражение его лица было довольно странным wordform_score "довольно" { прилагательное } = -1 // они как будто пришли издалека // ^^^^^^^^^ wordform_score "как будто" { наречие } = 2 // Лошадь встала на дыбы. wordform_score "встать на дыбы" { глагол } = 2 // мой друг как всегда был прав // ^^^^^^^^^^ wordform_score "как всегда" { наречие } = 2 // без кольца все стало как обычно // ^^^^^^^^^^ wordform_score "как обычно" { наречие } = 2 // однако совершенно необходимо время от времени менять темп. // ^^^^^^^^^^^^^^^^ wordform_score "время от времени" { наречие } = 5 // все равно уже сорвал // ^^^^^^^^^ wordform_score "все равно" { наречие } = 10 // деревья полностью закрывают серое небо // ^^^^^^^^^ wordform_score "полностью" { существительное } = -100 // волосы обоих были все еще мокрые. // ^^^^^^^ wordform_score "все еще" { наречие } = 2 // всего один день. wordform_score "день" { глагол } = -1 // ты все это прекрасно знаешь // ^^^^^^^ wordform_score "все это" { местоим_сущ } = 1 // Андрюха хотел жить на отшибе // ^^^^^^^^^ wordform_score "на отшибе" { наречие } = 1 // ПОЙМА vs ПОНЯТЬ wordform_score "пойму" { существительное } = -1 // лучше всего сделать это сразу // ^^^^^^^^^^^ wordform_score "лучше всего" { безлич_глагол } = 1 wordform_score "нахожусь" { глагол вид:соверш } = -2 wordform_score "находимся" { глагол вид:соверш } = -2 wordform_score "находится" { глагол вид:соверш } = -2 wordform_score "находитесь" { глагол вид:соверш } = -2 wordform_score "находился" { глагол вид:соверш } = -2 wordform_score "находилась" { глагол вид:соверш } = -2 wordform_score "находилось" { глагол вид:соверш } = -2 wordform_score "находились" { глагол вид:соверш } = -2 wordform_score "находим" { прилагательное } = -5 // В Полинезии находим культ черепов вождей. wordform_score пошли { глагол время:прошедшее } = 1 // мы пошли домой wordform_score пошли { глагол наклонение:побуд } = -1 // не пошли! wordform_score спешить { инфинитив вид:несоверш } = 1 // спеш^ить (торопиться) wordform_score спешил { глагол вид:несоверш }=1 wordform_score спешила { глагол вид:несоверш }=1 wordform_score спешили { глагол вид:несоверш }=1 wordform_score спеши { глагол вид:несоверш }=1 wordform_score спешить { инфинитив вид:соверш } =-2 // сп^ешить (спустить с коня на землю) wordform_score спешил { глагол вид:соверш }=-2 wordform_score спешила { глагол вид:соверш }=-2 wordform_score спешили { глагол вид:соверш }=-2 wordform_score лето { существительное род:ср } = 1 wordform_score лёт { существительное род:муж } = -5 // Коля, давай-ка выпей молока wordform_score выпей { глагол } = 1 wordform_score выпей { существительное } = -2 wordform_score видно { наречие } = -3 //wordform_score видно { прилагательное } = 0 //wordform_score видно { вводное } = -1 //wordform_score времени { существительное } = 1 wordform_score времени { глагол } = -5 // О факторе времени. //wordform_score перед { предлог } = 1 wordform_score перед { существительное } = -2 wordform_score на { предлог } = 1 wordform_score на { частица } = -10 wordform_score жил { существительное } = -1 // жила wordform_score жил { глагол } = 1 // жить wordform_score любой { существительное } = -1 // Люба wordform_score жал { существительное } = -10 // жало wordform_score жал { глагол } = 1 // жать wordform_score велик { прилагательное } = -1 // великий wordform_score велика { существительное } = -10 wordform_score велика { прилагательное } = 1 // великий wordform_score велики { существительное } = -10 wordform_score велики { прилагательное } = 1 // великий wordform_score были { существительное } = -10 wordform_score были { глагол } = 1 wordform_score весь { существительное } = -10 wordform_score весь { глагол } = -10 wordform_score весь { прилагательное } = 1 wordform_score вещей { существительное } = 1 wordform_score вещей { прилагательное } = -1 wordform_score времени { глагол } = -10 wordform_score времени { существительное } = 1 //wordform_score все { местоим_сущ } = 1 //wordform_score все { прилагательное } = 1 wordform_score все { наречие } = -2 wordform_score все { частица } = -2 wordform_score всей { глагол } = -10 wordform_score всей { прилагательное } = 1 //wordform_score дали { глагол } = 1 wordform_score дали { существительное } = -1 //wordform_score смог { глагол } = 1 wordform_score смог { существительное } = -1 wordform_score действительно { прилагательное } = -10 wordform_score действительно { наречие } = 1 // wordform_score дел { существительное } = 1 // wordform_score дел { глагол } = 1 wordform_score дело { существительное } = 1 wordform_score дело { глагол } = -1 // wordform_score дела { существительное } = 1 // wordform_score дела { глагол } = 1 wordform_score день { существительное } = 1 wordform_score день { глагол } = -10 wordform_score для { предлог } = 1 wordform_score для { деепричастие } = -10 wordform_score какая { прилагательное } = 1 wordform_score какая { деепричастие } = -10 wordform_score конечно { прилагательное } = -1 wordform_score конечно { наречие } = 1 wordform_score мая { существительное одуш:неодуш } = 1 wordform_score мая { существительное одуш:одуш } = -1 wordform_score моря { существительное } = 1 wordform_score моря { деепричастие } = -10 wordform_score моя { прилагательное } = 1 wordform_score моя { деепричастие } = -10 wordform_score особой { прилагательное } = 1 wordform_score особой { существительное } = -1 wordform_score пора { существительное } = -1 wordform_score пора { безлич_глагол } = 1 wordform_score при { предлог } = 1 wordform_score при { глагол } = -10 wordform_score разрыв { существительное } = 1 wordform_score разрыв { деепричастие } = -1 wordform_score совести { существительное число:ед } = 1 wordform_score совести { существительное число:мн } = -5 wordform_score совести { глагол } = -2 wordform_score хвои { глагол } = -2 // Кубдя подбросил хвои. wordform_score споров { существительное } = 1 wordform_score споров { деепричастие } = -1 wordform_score стать { существительное } = -1 wordform_score стать { инфинитив } = 1 wordform_score такая { деепричастие } = -10 // такать wordform_score такая { прилагательное } = 1 wordform_score три { глагол } = -1 // тереть wordform_score три { числительное } = 1 wordform_score тут { существительное одуш:неодуш } = -10 // тут (тутовое дерево) wordform_score тут { наречие } = 1 wordform_score уж { частица } = 1 wordform_score уж { наречие } = 1 wordform_score уж { существительное } = -2 wordform_score уже { наречие степень:атриб } = 1 wordform_score уже { прилагательное } = -3 // узкий wordform_score уже { существительное } = -2 wordform_score уже { наречие степень:сравн } = -5 // узко wordform_score хотя { деепричастие } = -10 // хотеть wordform_score хотя { союз } = 1 // краткие формы среднего рода прилагательных используются очень редко, в отличие // от буквально совпадающих с ними наречий #define PreferAdverb(x) \ #begin //wordform_score x { наречие } = 2000000 wordform_score x { прилагательное } = -2 #end PreferAdverb( "абсолютно" ) PreferAdverb( "абстрактно" ) PreferAdverb( "абсурдно" ) PreferAdverb( "аварийно" ) PreferAdverb( "автоматично" ) PreferAdverb( "авторитарно" ) PreferAdverb( "авторитетно" ) PreferAdverb( "азартно" ) PreferAdverb( "аккуратно" ) PreferAdverb( "активно" ) PreferAdverb( "актуально" ) PreferAdverb( "алогично" ) PreferAdverb( "амбивалентно" ) PreferAdverb( "аномально" ) PreferAdverb( "анонимно" ) PreferAdverb( "аргументировано" ) PreferAdverb( "аристократично" ) PreferAdverb( "архиважно" ) PreferAdverb( "аскетично" ) PreferAdverb( "афористично" ) PreferAdverb( "капризно" ) PreferAdverb( "кардинально" ) PreferAdverb( "карикатурно" ) PreferAdverb( "категорично" ) PreferAdverb( "качественно" ) PreferAdverb( "классно" ) PreferAdverb( "комично" ) PreferAdverb( "комфортабельно" ) PreferAdverb( "комфортно" ) PreferAdverb( "конвульсивно" ) PreferAdverb( "конечно" ) PreferAdverb( "конкретно" ) PreferAdverb( "конструктивно" ) PreferAdverb( "контрастно" ) PreferAdverb( "концептуально" ) PreferAdverb( "корректно" ) PreferAdverb( "кратковременно" ) PreferAdverb( "крестообразно" ) PreferAdverb( "кристально" ) PreferAdverb( "круглосуточно" ) PreferAdverb( "курьезно" ) PreferAdverb( "кучно" ) PreferAdverb( "комплиментарно" ) PreferAdverb( "агрессивно" ) PreferAdverb( "адекватно" ) PreferAdverb( "алчно" ) PreferAdverb( "амбициозно" ) PreferAdverb( "аморально" ) PreferAdverb( "аналогично" ) PreferAdverb( "анекдотично" ) PreferAdverb( "апатично" ) PreferAdverb( "аполитично" ) PreferAdverb( "артистично" ) PreferAdverb( "асимметрично" ) PreferAdverb( "ассоциативно" ) PreferAdverb( "красно" ) PreferAdverb( "конфиденциально" ) PreferAdverb( "клятвенно" ) PreferAdverb( "краткосрочно" ) PreferAdverb( "круглогодично" ) PreferAdverb( "когерентно" ) PreferAdverb( "конъюнктурно" ) PreferAdverb( "конформно" ) PreferAdverb( "асинхронно" ) PreferAdverb( "аритмично" ) PreferAdverb( "альтруистично" ) PreferAdverb( "критично" ) PreferAdverb( "авантюрно" ) PreferAdverb( "автобиографично" ) PreferAdverb( "автономно" ) PreferAdverb( "аддитивно" ) PreferAdverb( "ажурно" ) PreferAdverb( "азбучно" ) PreferAdverb( "академично" ) PreferAdverb( "аллегорично" ) PreferAdverb( "альтернативно" ) PreferAdverb( "аморфно" ) PreferAdverb( "антагонистично" ) PreferAdverb( "антинаучно" ) PreferAdverb( "антиобщественно" ) PreferAdverb( "аппетитно" ) PreferAdverb( "ароматно" ) PreferAdverb( "архаично" ) PreferAdverb( "атипично" ) PreferAdverb( "аутентично" ) PreferAdverb( "каверзно" ) PreferAdverb( "капитально" ) PreferAdverb( "каплеобразно" ) PreferAdverb( "катастрофично" ) PreferAdverb( "келейно" ) PreferAdverb( "клешнеобразно" ) PreferAdverb( "клиновидно" ) PreferAdverb( "клинообразно" ) PreferAdverb( "коварно" ) PreferAdverb( "комедийно" ) PreferAdverb( "консервативно" ) PreferAdverb( "конституционно" ) PreferAdverb( "конусовидно" ) PreferAdverb( "конусообразно" ) PreferAdverb( "корыстно" ) PreferAdverb( "косвенно" ) PreferAdverb( "косноязычно" ) PreferAdverb( "кошмарно" ) PreferAdverb( "кощунственно" ) PreferAdverb( "красочно" ) PreferAdverb( "криводушно" ) PreferAdverb( "кровожадно" ) PreferAdverb( "крохотно" ) PreferAdverb( "крупно" ) PreferAdverb( "культурно" ) PreferAdverb( "куполообразно" ) PreferAdverb( "кустарно" ) PreferAdverb( "акцентировано" ) /*----------------------- select F1.name as word, Concat( '// ', C1.name, ':', E1.name, '{} и ', C2.name, ':', E2.name, '{}' ) from sg_entry E1, sg_entry E2, sg_form F1, sg_form F2, sg_class C1, sg_class C2 where E1.id_class!=E2.id_class and E1.name!='???' and F1.id_entry=E1.id and F2.id_entry=E2.id and F1.name=F2.name and C1.id=E1.id_class and C2.id=E2.id_class and E1.id<E2.id order by F1.name -------------------------*/ wordform_score "атакуем" { глагол } = 1 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{} wordform_score "атакуем" { прилагательное } = -10 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{} wordform_score "классифицируем" { глагол } = 1 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} wordform_score "классифицируем" { прилагательное } = -10 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} wordform_score "компенсируем" { глагол } = 1 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} wordform_score "компенсируем" { прилагательное } = -10 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} wordform_score "Коля" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ДЕЕПРИЧАСТИЕ:коля{} wordform_score "Коля" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Коли" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и СОЮЗ:коли{} wordform_score "Коли" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Колю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Колю" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Кати" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{} wordform_score "Кати" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{} wordform_score "куплю" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{} wordform_score "куплю" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{} wordform_score "крали" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{} wordform_score "крали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{} wordform_score "крести" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{} wordform_score "крести" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{} wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыла" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыла" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { ГЛАГОЛ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "ком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "ком" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "Костя" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{} wordform_score "Костя" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{} wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{} wordform_score "кувырком" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{} wordform_score "колея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{} wordform_score "колея" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{} wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канал" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канала" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "автостопом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{} wordform_score "автостопом" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{} wordform_score "Ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{} wordform_score "Ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{} wordform_score "кладу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{} wordform_score "кладу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{} wordform_score "клей" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{} wordform_score "клей" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{} wordform_score "клея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{} wordform_score "клея" { ДЕЕПРИЧАСТИЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{} wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{} wordform_score "кубарем" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{} wordform_score "калачиком" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{} wordform_score "калачиком" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{} wordform_score "ковали" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{} wordform_score "ковали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{} wordform_score "Алле" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{} wordform_score "Алле" { ЧАСТИЦА } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{} wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { МЕСТОИМ_СУЩ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кисла" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисла" { ГЛАГОЛ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисло" { наречие } = 2 wordform_score "кисло" { ПРИЛАГАТЕЛЬНОЕ } = -2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисло" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "конвертируем" { ПРИЛАГАТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{} wordform_score "конвертируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{} wordform_score "клади" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{} wordform_score "клади" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{} wordform_score "копи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{} wordform_score "копи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{} wordform_score "крепи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{} wordform_score "крепи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{} wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{} wordform_score "крошку" { НАРЕЧИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{} wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "какой" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} //wordform_score "какой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} wordform_score "какою" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} wordform_score "какою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} // СУЩЕСТВИТЕЛЬНОЕ:кака{} и СОЮЗ:как{} wordform_score "как" { СОЮЗ } = 3 wordform_score "как" { НАРЕЧИЕ } = 2 wordform_score "как" { ЧАСТИЦА } = 1 wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10 wordform_score "ковка" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{} wordform_score "ковка" { ПРИЛАГАТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{} wordform_score "кучу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{} wordform_score "кучу" { ГЛАГОЛ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{} wordform_score "кручу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{} wordform_score "кручу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{} wordform_score "круче" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{} wordform_score "круче" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{} wordform_score "круче" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ПРИЛАГАТЕЛЬНОЕ:крутой{} wordform_score "как" { СОЮЗ } = 3 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{} wordform_score "как" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{} wordform_score "как" { ЧАСТИЦА } = 0 // НАРЕЧИЕ:как{} и СОЮЗ:как{} wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:как{} и ЧАСТИЦА:как{} wordform_score "кругом" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{} wordform_score "кругом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{} wordform_score "кувырком" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{} wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{} wordform_score "каплю" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{} wordform_score "каплю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{} wordform_score "крошечку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{} wordform_score "крошечку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{} wordform_score "крошку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{} wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{} wordform_score "кубарем" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{} wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{} wordform_score "кипуче" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{} wordform_score "кипуче" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{} wordform_score "куце" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{} wordform_score "куце" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{} wordform_score "антенной" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{} wordform_score "антенной" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{} wordform_score "анализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{} wordform_score "анализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{} wordform_score "ассоциируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{} wordform_score "ассоциируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{} wordform_score "культивируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:культивируемый{} и ГЛАГОЛ:культивировать{} wordform_score "контролируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:контролируемый{} и ГЛАГОЛ:контролировать{} wordform_score "автоматизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{} wordform_score "автоматизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{} wordform_score "адаптируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{} wordform_score "адаптируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{} wordform_score "адресуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{} wordform_score "адресуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{} wordform_score "аккумулируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{} wordform_score "аккумулируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{} wordform_score "акцептуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{} wordform_score "акцептуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{} wordform_score "акционируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{} wordform_score "акционируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{} wordform_score "амортизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{} wordform_score "амортизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{} wordform_score "арендуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{} wordform_score "арендуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{} wordform_score "афишируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{} wordform_score "афишируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{} wordform_score "капитализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{} wordform_score "капитализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{} wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "комментируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{} wordform_score "комментируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{} wordform_score "коммутируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{} wordform_score "коммутируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{} wordform_score "конвоируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{} wordform_score "конвоируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{} wordform_score "координируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{} wordform_score "координируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{} wordform_score "котируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{} wordform_score "котируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{} wordform_score "кредитуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{} wordform_score "кредитуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{} wordform_score "критикуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{} wordform_score "критикуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{} wordform_score "курируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{} wordform_score "курируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{} wordform_score "корректируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{} wordform_score "корректируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{} wordform_score "ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{} wordform_score "ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{} wordform_score "кочевым" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{} wordform_score "кочевым" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{} wordform_score "атакуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{} wordform_score "атакуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{} wordform_score "казним" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{} wordform_score "казним" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{} wordform_score "качаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{} wordform_score "качаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{} wordform_score "кусаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{} wordform_score "кусаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{} wordform_score "компенсируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{} wordform_score "компенсируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{} wordform_score "караем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{} wordform_score "караем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{} wordform_score "командируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{} wordform_score "командируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{} wordform_score "конструируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{} wordform_score "конструируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{} wordform_score "консультируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{} wordform_score "консультируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{} wordform_score "кидаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{} wordform_score "кидаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{} wordform_score "акцентируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{} wordform_score "акцентируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{} wordform_score "колонизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{} wordform_score "колонизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{} wordform_score "крымском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{} wordform_score "крымском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{} wordform_score "каспийском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{} wordform_score "каспийском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{} wordform_score "амурском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{} wordform_score "амурском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{} wordform_score "архангельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{} wordform_score "архангельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{} wordform_score "курильском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{} wordform_score "курильском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{} wordform_score "кировском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{} wordform_score "кировском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{} wordform_score "козельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{} wordform_score "козельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{} wordform_score "курском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{} wordform_score "курском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{} wordform_score "калининском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{} wordform_score "калининском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{} wordform_score "красноярском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{} wordform_score "красноярском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{} wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкою" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{} wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{} wordform_score "адыгейском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{} wordform_score "адыгейском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{} wordform_score "комсомольском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{} wordform_score "комсомольском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{} wordform_score "апшеронском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{} wordform_score "апшеронском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{} wordform_score "тайна" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:тайный{} wordform_score "тайна" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:тайна{} wordform_score "коробило" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробило" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробит" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробит" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "казалось" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{} wordform_score "казалось" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{} wordform_score "канал" { ГЛАГОЛ } = -5 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канала" { ГЛАГОЛ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "чай" { ГЛАГОЛ } = -10 // чаять wordform_score "чай" { СУЩЕСТВИТЕЛЬНОЕ } = 0 // чай wordform_score "чай" { частица } = -2 // чай wordform_score "чай" { наречие } = -5 wordform_score "готов" { прилагательное } = 1 wordform_score "готов" { существительное } = -1 wordform_score "извести" { инфинитив } = -1 wordform_score "извести" { существительное } = 1 wordform_score "нашли" { наклонение:изъяв } = 1 wordform_score "нашли" { наклонение:побуд } = -5 // ---- wordform_score "брехни" { глагол } = -1 // брехня брехни --> брехнуть брехни wordform_score "бузил" { существительное } = -1 // бузила бузил --> бузить бузил wordform_score "бурей" { глагол } = -1 // буря бурей --> буреть бурей wordform_score "бюллетень" { глагол } = -1 // бюллетень бюллетень --> бюллетенить бюллетень wordform_score "возрасту" { глагол } = -1 // возраст возрасту --> возрасти возрасту wordform_score "воплю" { глагол } = -1 // вопль воплю --> вопить воплю wordform_score "врали" { существительное } = -1 // враль врали --> врать врали wordform_score "гвозди" { глагол } = -1 // гвоздь гвозди --> гвоздить гвозди wordform_score "Глашу" { глагол } = -1 // Глаша Глашу --> гласить глашу wordform_score "голубей" { глагол } = -1 // голубь голубей --> голубеть голубей wordform_score "гряду" { глагол } = -1 // гряда гряду --> грясти гряду wordform_score "Дорою" { существительное } = -1 // Дора Дорою --> дорыть дорою wordform_score "дох" { глагол } = -1 // доха дох --> дохнуть дох wordform_score "драконят" { существительное } = -1 // драконенок драконят --> драконить драконят wordform_score "дублю" { глагол } = -1 // дубль дублю --> дубить дублю wordform_score "дули" { существительное } = -1 // дуля дули --> дуть дули wordform_score "ежу" { глагол } = -1 // еж ежу --> ежить ежу wordform_score "жал" { существительное } = -1 // жало жал --> жать жал wordform_score "жигану" { глагол } = -1 // жиган жигану --> жигануть жигану wordform_score "завали" { существительное } = -1 // заваль завали --> завалить завали wordform_score "замшей" { глагол } = -1 // замша замшей --> замшеть замшей wordform_score "зарей" { глагол } = -1 // заря зарей --> зареять зарей wordform_score "затей" { глагол } = -1 // затея затей --> затеять затей wordform_score "затею" { глагол } = -1 // затея затею --> затеять затею wordform_score "затону" { существительное } = -1 // затон затону --> затонуть затону wordform_score "знахарю" { глагол } = -1 // знахарь знахарю --> знахарить знахарю wordform_score "изморозь" { глагол } = -1 // изморозь изморозь --> изморозить изморозь wordform_score "канитель" { глагол } = -1 // канитель канитель --> канителить канитель wordform_score "ковали" { существительное } = -1 // коваль ковали --> ковать ковали wordform_score "кучу" { глагол } = -1 // куча кучу --> кутить кучу wordform_score "лохмачу" { существительное } = -1 // лохмач лохмачу --> лохматить лохмачу wordform_score "матерей" { глагол } = -5 // мать матерей --> матереть матерей wordform_score "матери" { глагол } = -5 // мать матери --> материть матери wordform_score "метель" { глагол } = -1 // метель метель --> метелить метель wordform_score "мини" { глагол } = -1 // мини мини --> минуть мини wordform_score "минут" { глагол } = -1 // минута минут --> минуть минут wordform_score "молоди" { глагол } = -1 // молодь молоди --> молодить молоди wordform_score "батрачат" { существительное } = -1 // батрачонок батрачат --> батрачить батрачат wordform_score "бузила" { существительное } = -1 // бузила бузила --> бузить бузила wordform_score "времени" { глагол } = -1 // время времени --> временить времени wordform_score "дурней" { глагол } = -1 // дурень дурней --> дурнеть дурней wordform_score "наймите" { существительное } = -1 // наймит наймите --> нанять наймите wordform_score "накипи" { глагол } = -1 // накипь накипи --> накипеть накипи wordform_score "нарвал" { существительное } = -1 // нарвал нарвал --> нарвать нарвал wordform_score "нарвала" { существительное } = -1 // нарвал нарвала --> нарвать нарвала wordform_score "нарой" { существительное } = -1 // нара нарой --> нарыть нарой wordform_score "пари" { глагол } = -1 // пари пари --> парить пари wordform_score "пастушат" { глагол } = -1 // пастушонок пастушат --> пастушить пастушат wordform_score "пасу" { существительное } = -1 // пас пасу --> пасти пасу wordform_score "пень" { глагол } = -1 // пень пень --> пенить пень wordform_score "пеню" { глагол } = -1 // пеня пеню --> пенить пеню wordform_score "передам" { существительное } = -1 // перед передам --> передать передам wordform_score "печаль" { глагол } = -1 // печаль печаль --> печалить печаль wordform_score "подтеки" { глагол } = -1 // подтек подтеки --> подтечь подтеки wordform_score "постригу" { существительное } = -1 // постриг постригу --> постричь постригу wordform_score "проем" { глагол } = -1 // проем проем --> проесть проем wordform_score "простой" { глагол } = -1 // простой простой --> простоять простой wordform_score "пряди" { глагол } = -1 // прядь пряди --> прясть пряди wordform_score "разъем" { глагол } = -1 // разъем разъем --> разъесть разъем wordform_score "ржу" { существительное } = -1 // ржа ржу --> ржать ржу wordform_score "ругани" { глагол } = -1 // ругань ругани --> ругануть ругани wordform_score "сбои" { глагол } = -1 // сбой сбои --> сбоить сбои wordform_score "секретарь" { глагол } = -1 // секретарь секретарь --> секретарить секретарь wordform_score "скину" { существительное } = -1 // скин скину --> скинуть скину wordform_score "слесарь" { глагол } = -1 // слесарь слесарь --> слесарить слесарь wordform_score "случаем" { глагол } = -1 // случай случаем --> случать случаем wordform_score "соловей" { глагол } = -1 // соловей соловей --> соловеть соловей wordform_score "спирали" { глагол } = -1 // спираль спирали --> спирать спирали wordform_score "старь" { глагол } = -1 // старь старь --> старить старь wordform_score "струи" { глагол } = -1 // струя струи --> струить струи wordform_score "такелажу" { глагол } = -1 // такелаж такелажу --> такелажить такелажу wordform_score "участи" { глагол } = -1 // участь участи --> участить участи wordform_score "хмелю" { глагол } = -10 // хмель хмелю --> хмелить хмелю wordform_score "чаем" { глагол } = -10 // чай чаем --> чаять чаем wordform_score "замшею" { глагол } = -1 // замша замшею --> замшеть замшею wordform_score "зелени" { глагол } = -1 // зелень зелени --> зеленить зелени wordform_score "знахарь" { глагол } = -1 // знахарь знахарь --> знахарить знахарь wordform_score "канифоль" { глагол } = -1 // канифоль канифоль --> канифолить канифоль wordform_score "лужу" { глагол } = -1 // лужа лужу --> лудить лужу wordform_score "матерей" { глагол } = -1 // матерь матерей --> матереть матерей wordform_score "матери" { глагол } = -1 // матерь матери --> материть матери wordform_score "мелей" { глагол } = -1 // мель мелей --> мелеть мелей wordform_score "мыло" { глагол } = -1 // мыло мыло --> мыть мыло wordform_score "обезьянят" { существительное } = -1 // обезьяненок обезьянят --> обезьянить обезьянят wordform_score "объем" { глагол } = -1 // объем объем --> объесть объем wordform_score "осени" { глагол } = -1 // осень осени --> осенить осени wordform_score "отмели" { глагол } = -1 // отмель отмели --> отмолоть отмели wordform_score "перла" { существительное } = -1 // перл перла --> переть перла wordform_score "пил" { существительное } = -1 // пила пил --> пить пил wordform_score "пищали" { существительное } = -1 // пищаль пищали --> пищать пищали wordform_score "поволок" { существительное } = -1 // поволока поволок --> поволочь поволок wordform_score "поволоку" { существительное } = -1 // поволока поволоку --> поволочь поволоку wordform_score "покой" { глагол } = -5 // покой покой --> покоить покой wordform_score "покою" { глагол } = -5 // покой покою --> покоить покою wordform_score "полет" { глагол } = -1 // полет полет --> полоть полет wordform_score "полете" { глагол } = -1 // полет полете --> полоть полете wordform_score "полю" { глагол } = -1 // поле полю --> полоть полю wordform_score "примеси" { глагол } = -1 // примесь примеси --> примесить примеси wordform_score "примету" { глагол } = -1 // примета примету --> примести примету wordform_score "припас" { существительное } = -1 // припас припас --> припасти припас wordform_score "продела" { существительное } = -1 // продел продела --> продеть продела wordform_score "просек" { существительное } = -1 // просека просек --> просечь просек wordform_score "пущу" { существительное } = -1 // пуща пущу --> пустить пущу wordform_score "пьяни" { глагол } = -1 // пьянь пьяни --> пьянить пьяни wordform_score "сбою" { глагол } = -1 // сбой сбою --> сбоить сбою wordform_score "свечу" { глагол } = -1 // свеча свечу --> светить свечу wordform_score "секретарю" { глагол } = -1 // секретарь секретарю --> секретарить секретарю wordform_score "случай" { глагол } = -5 // случай случай --> случать случай wordform_score "случаю" { глагол } = -5 // случай случаю --> случать случаю wordform_score "слюни" { глагол } = -1 // слюна слюни --> слюнить слюни wordform_score "смог" { существительное } = -1 // смог смог --> смочь смог wordform_score "смогу" { существительное } = -1 // смог смогу --> смочь смогу wordform_score "собачат" { существительное } = -1 // собаченок собачат --> собачить собачат wordform_score "совести" { глагол } = -1 // совесть совести --> совестить совести wordform_score "спас" { существительное } = -1 // спас спас --> спасти спас wordform_score "стай" { глагол } = -1 // стая стай --> стаять стай wordform_score "стаю" { глагол } = -1 // стая стаю --> стаять стаю wordform_score "струю" { глагол } = -1 // струя струю --> струить струю wordform_score "стужу" { глагол } = -1 // стужа стужу --> студить стужу wordform_score "сучат" { существительное } = -1 // сучонок сучат --> сучить сучат wordform_score "тлей" { глагол } = -1 // тля тлей --> тлеть тлей wordform_score "толщу" { глагол } = -1 // толща толщу --> толстить толщу wordform_score "царю" { глагол } = -4 // царь царю --> царить царю ==> Ну а поздно вечером довелось удивиться и царю. wordform_score "чащу" { глагол } = -1 // чаща чащу --> частить чащу wordform_score "чаю" { глагол } = -10 // чай чаю --> чаять чаю wordform_score "ширь" { глагол } = -1 // ширь ширь --> ширить ширь wordform_score "штурману" { глагол } = -1 // штурман штурману --> штурмануть штурману wordform_score "щурят" { существительное } = -1 // щуренок щурят --> щурить щурят wordform_score "гноя" { деепричастие } = -4 // гной гноя --> гноя гноя wordform_score "гостя" { деепричастие } = -1 // гость гостя --> гостя гостя wordform_score "душа" { деепричастие } = -1 // душ душа --> душа душа wordform_score "катя" { деепричастие } = -4 // Катя Катя --> катя катя wordform_score "колея" { деепричастие } = -1 // колея колея --> колея колея wordform_score "костя" { деепричастие } = -1 // Костя Костя --> костя костя wordform_score "нарыв" { деепричастие } = -1 // нарыв нарыв --> нарыв нарыв wordform_score "отлив" { деепричастие } = -1 // отлив отлив --> отлив отлив wordform_score "отпоров" { существительное } = -1 // отпор отпоров --> отпоров отпоров wordform_score "отрыв" { деепричастие } = -1 // отрыв отрыв --> отрыв отрыв wordform_score "подлив" { существительное } = -1 // подлива подлив --> подлив подлив wordform_score "покоя" { деепричастие } = -1 // покой покоя --> покоя покоя wordform_score "прилив" { деепричастие } = -1 // прилив прилив --> прилив прилив wordform_score "пузыря" { деепричастие } = -1 // пузырь пузыря --> пузыря пузыря wordform_score "руля" { деепричастие } = -1 // руль руля --> руля руля wordform_score "селя" { деепричастие } = -1 // сель селя --> селя селя wordform_score "случая" { деепричастие } = -1 // случай случая --> случая случая wordform_score "сторожа" { деепричастие } = -1 // сторож сторожа --> сторожа сторожа wordform_score "суша" { деепричастие } = -1 // суша суша --> суша суша wordform_score "туша" { деепричастие } = -1 // туш туша --> туша туша wordform_score "хмеля" { деепричастие } = -1 // хмель хмеля --> хмеля хмеля wordform_score "валя" { деепричастие } = -1 // Валя Валя --> валя валя wordform_score "варя" { деепричастие } = -1 // Варя Варя --> варя варя wordform_score "гвоздя" { деепричастие } = -1 // гвоздь гвоздя --> гвоздя гвоздя wordform_score "голубя" { деепричастие } = -1 // голубь голубя --> голубя голубя wordform_score "горя" { деепричастие } = -1 // горе горя --> горя горя wordform_score "клея" { деепричастие } = -1 // клей клея --> клея клея wordform_score "неволя" { деепричастие } = -1 // неволя неволя --> неволя неволя wordform_score "отколов" { существительное } = -1 // откол отколов --> отколов отколов wordform_score "переборов" { существительное } = -1 // перебор переборов --> переборов переборов wordform_score "подлив" { существительное } = -1 // подлив подлив --> подлив подлив wordform_score "подрыв" { деепричастие } = -1 // подрыв подрыв --> подрыв подрыв wordform_score "полив" { деепричастие } = -1 // полив полив --> полив полив wordform_score "пошив" { деепричастие } = -1 // пошив пошив --> пошив пошив wordform_score "чая" { деепричастие } = -10 // чай чая --> чая чая wordform_score "струя" { деепричастие } = -1 // струя струя --> струя струя wordform_score "белков" { прилагательное } = -1 // белок белков --> белковый белков wordform_score "витой" { существительное } = -1 // Вита Витой --> витой витой wordform_score "вожатом" { прилагательное } = -1 // вожатый вожатом --> вожатый вожатом wordform_score "вожатым" { прилагательное } = -1 // вожатый вожатым --> вожатый вожатым wordform_score "вожатых" { прилагательное } = -1 // вожатый вожатых --> вожатый вожатых wordform_score "гола" { прилагательное } = -1 // гол гола --> голый гола wordform_score "вороной" { прилагательное } = -1 // ворона вороной --> вороной вороной wordform_score "голы" { прилагательное } = -1 // гол голы --> голый голы wordform_score "гусиной" { существительное } = -1 // Гусина Гусиной --> гусиный гусиной wordform_score "гусиным" { существительное } = -1 // Гусин Гусиным --> гусиный гусиным wordform_score "гусиными" { существительное } = -1 // Гусин Гусиными --> гусиный гусиными wordform_score "добро" { прилагательное } = -1 // добро добро --> добрый добро wordform_score "долги" { прилагательное } = -1 // долг долги --> долгий долги wordform_score "готов" { существительное } = -1 // гот готов --> готовый готов wordform_score "звонки" { прилагательное } = -1 // звонок звонки --> звонкий звонки wordform_score "звонок" { прилагательное } = -1 // звонок звонок --> звонкий звонок wordform_score "лаком" { прилагательное } = -1 // лак лаком --> лакомый лаком wordform_score "лев" { прилагательное } = -1 // лев лев --> левый лев wordform_score "лишаем" { прилагательное } = -1 // лишай лишаем --> лишаемый лишаем wordform_score "сладка" { существительное } = -10 // сладка сладка --> сладкий сладка wordform_score "сладкой" { существительное } = -1 // сладка сладкой --> сладкий сладкой wordform_score "сладкою" { существительное } = -1 // сладка сладкою --> сладкий сладкою wordform_score "сладок" { существительное } = -1 // сладка сладок --> сладкий сладок wordform_score "темен" { существительное } = -1 // темя темен --> темный темен wordform_score "тонной" { прилагательное } = -1 // тонна тонной --> тонный тонной wordform_score "ужат" { существительное } = -1 // ужонок ужат --> ужатый ужат wordform_score "этой" { существительное } = -5 // эта этой --> этот этой wordform_score "рада" { существительное } = -1 // Рада Рада --> рад рада wordform_score "рады" { существительное } = -1 // Рада Рады --> рад рады wordform_score "столиком" { прилагательное } = -1 // столик столиком --> столикий столиком wordform_score "теми" { существительное } = -1 // темь теми --> тот теми wordform_score "тонною" { прилагательное } = -1 // тонна тонною --> тонный тонною wordform_score "ужата" { существительное } = -1 // ужонок ужата --> ужатый ужата wordform_score "эта" { существительное } = -3 // эта эта --> этот эта wordform_score "этою" { существительное } = -1 // эта этою --> этот этою wordform_score "эту" { существительное } = -3 // эта эту --> этот эту // ------------------------ // Для имен и некоторых существительных на -ИЕ варианты множественного числа // обычно не употребляются, поэтому мы можем априори предположить пониженную достоверность. // Этот макрос далее используется для перечисления таких слов. #define DiscountPlural(w) wordform_score w { существительное число:мн } = -2 /* -- список форм получен из SQL словаря запросом: select distinct 'DiscountPlural('+F.name+')' from sg_entry E, sg_link L, sg_entry E2, sg_entry_coord EC, sg_form F, sg_form_coord FC where E.id_class=9 and L.id_entry1=E.id and L.istate=50 and E2.id=L.id_entry2 and E2.name='ИМЯ' and EC.id_entry=E.id and EC.icoord=14 and EC.istate=1 and F.id_entry=E.id and FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1 */ DiscountPlural(Авдотий) DiscountPlural(Авдотьи) DiscountPlural(Авдотьям) DiscountPlural(Авдотьями) DiscountPlural(Авдотьях) DiscountPlural(Агафий) DiscountPlural(Агафьи) DiscountPlural(Агафьям) DiscountPlural(Агафьями) DiscountPlural(Агафьях) DiscountPlural(Агнии) DiscountPlural(Агний) DiscountPlural(Агниям) DiscountPlural(Агниями) DiscountPlural(Агниях) DiscountPlural(Азалии) DiscountPlural(Азалий) DiscountPlural(Азалиям) DiscountPlural(Азалиями) DiscountPlural(Азалиях) DiscountPlural(Аксиний) DiscountPlural(Аксиньи) DiscountPlural(Аксиньям) DiscountPlural(Аксиньями) DiscountPlural(Аксиньях) DiscountPlural(Амалии) DiscountPlural(Амалий) DiscountPlural(Амалиям) DiscountPlural(Амалиями) DiscountPlural(Амалиях) DiscountPlural(Анастасии) DiscountPlural(Анастасий) DiscountPlural(Анастасиям) DiscountPlural(Анастасиями) DiscountPlural(Анастасиях) DiscountPlural(Анисий) DiscountPlural(Анисьи) DiscountPlural(Анисьям) DiscountPlural(Анисьями) DiscountPlural(Анисьях) DiscountPlural(Аполлинарии) DiscountPlural(Аполлинарий) DiscountPlural(Аполлинариям) DiscountPlural(Аполлинариями) DiscountPlural(Аполлинариях) DiscountPlural(Апраксии) DiscountPlural(Апраксий) DiscountPlural(Апраксиям) DiscountPlural(Апраксиями) DiscountPlural(Апраксиях) DiscountPlural(Валерии) DiscountPlural(Валерий) DiscountPlural(Валериям) DiscountPlural(Валериями) DiscountPlural(Валериях) DiscountPlural(Виктории) DiscountPlural(Викторий) DiscountPlural(Викториям) DiscountPlural(Викториями) DiscountPlural(Викториях) DiscountPlural(Виргинии) DiscountPlural(Виргиний) DiscountPlural(Виргиниям) DiscountPlural(Виргиниями) DiscountPlural(Виргиниях) DiscountPlural(Виталии) DiscountPlural(Виталий) DiscountPlural(Виталиям) DiscountPlural(Виталиями) DiscountPlural(Виталиях) DiscountPlural(Гликерии) DiscountPlural(Гликерий) DiscountPlural(Гликериям) DiscountPlural(Гликериями) DiscountPlural(Гликериях) DiscountPlural(Гортензии) DiscountPlural(Гортензий) DiscountPlural(Гортензиям) DiscountPlural(Гортензиями) DiscountPlural(Гортензиях) DiscountPlural(Дарий) DiscountPlural(Дарьи) DiscountPlural(Дарьям) DiscountPlural(Дарьями) DiscountPlural(Дарьях) DiscountPlural(Денисии) DiscountPlural(Денисий) DiscountPlural(Денисиям) DiscountPlural(Денисиями) DiscountPlural(Денисиях) DiscountPlural(Евгении) DiscountPlural(Евгений) DiscountPlural(Евгениям) DiscountPlural(Евгениями) DiscountPlural(Евгениях) DiscountPlural(Евдокии) DiscountPlural(Евдокий) DiscountPlural(Евдокиям) DiscountPlural(Евдокиями) DiscountPlural(Евдокиях) DiscountPlural(Евдоксии) DiscountPlural(Евдоксий) DiscountPlural(Евдоксиям) DiscountPlural(Евдоксиями) DiscountPlural(Евдоксиях) DiscountPlural(Евлалии) DiscountPlural(Евлалий) DiscountPlural(Евлалиям) DiscountPlural(Евлалиями) DiscountPlural(Евлалиях) DiscountPlural(Евлампии) DiscountPlural(Евлампий) DiscountPlural(Евлампиям) DiscountPlural(Евлампиями) DiscountPlural(Евлампиях) DiscountPlural(Евпраксии) DiscountPlural(Евпраксий) DiscountPlural(Евпраксиям) DiscountPlural(Евпраксиями) DiscountPlural(Евпраксиях) DiscountPlural(Евстолии) DiscountPlural(Евстолий) DiscountPlural(Евстолиям) DiscountPlural(Евстолиями) DiscountPlural(Евстолиях) DiscountPlural(Евфимии) DiscountPlural(Евфимий) DiscountPlural(Евфимиям) DiscountPlural(Евфимиями) DiscountPlural(Евфимиях) DiscountPlural(Евфросинии) DiscountPlural(Евфросиний) DiscountPlural(Евфросиниям) DiscountPlural(Евфросиниями) DiscountPlural(Евфросиниях) DiscountPlural(Епистимии) DiscountPlural(Епистимий) DiscountPlural(Епистимиям) DiscountPlural(Епистимиями) DiscountPlural(Епистимиях) DiscountPlural(Ефимии) DiscountPlural(Ефимий) DiscountPlural(Ефимиям) DiscountPlural(Ефимиями) DiscountPlural(Ефимиях) DiscountPlural(Ефросинии) DiscountPlural(Ефросиний) DiscountPlural(Ефросиниям) DiscountPlural(Ефросиниями) DiscountPlural(Ефросиниях) DiscountPlural(Ефросиньи) DiscountPlural(Ефросиньям) DiscountPlural(Ефросиньями) DiscountPlural(Ефросиньях) DiscountPlural(Зиновии) DiscountPlural(Зиновий) DiscountPlural(Зиновиям) DiscountPlural(Зиновиями) DiscountPlural(Зиновиях) DiscountPlural(Ии) DiscountPlural(Ий) DiscountPlural(Иям) DiscountPlural(Иями) DiscountPlural(Иях) DiscountPlural(Калерии) DiscountPlural(Калерий) DiscountPlural(Калериям) DiscountPlural(Калериями) DiscountPlural(Калериях) DiscountPlural(Клавдии) DiscountPlural(Клавдий) DiscountPlural(Клавдиям) DiscountPlural(Клавдиями) DiscountPlural(Клавдиях) DiscountPlural(Конкордии) DiscountPlural(Конкордий) DiscountPlural(Конкордиям) DiscountPlural(Конкордиями) DiscountPlural(Конкордиях) DiscountPlural(Констанции) DiscountPlural(Констанций) DiscountPlural(Констанциям) DiscountPlural(Констанциями) DiscountPlural(Констанциях) DiscountPlural(Корнелии) DiscountPlural(Корнелий) DiscountPlural(Корнелиям) DiscountPlural(Корнелиями) DiscountPlural(Корнелиях) DiscountPlural(Ксении) DiscountPlural(Ксений) DiscountPlural(Ксениям) DiscountPlural(Ксениями) DiscountPlural(Ксениях) DiscountPlural(Леокадии) DiscountPlural(Леокадий) DiscountPlural(Леокадиям) DiscountPlural(Леокадиями) DiscountPlural(Леокадиях) DiscountPlural(Лидии) DiscountPlural(Лидий) DiscountPlural(Лидиям) DiscountPlural(Лидиями) DiscountPlural(Лидиях) DiscountPlural(Лии) DiscountPlural(Лий) DiscountPlural(Лилии) DiscountPlural(Лилий) DiscountPlural(Лилиям) DiscountPlural(Лилиями) DiscountPlural(Лилиях) DiscountPlural(Лиям) DiscountPlural(Лиями) DiscountPlural(Лиях) DiscountPlural(Лукерий) DiscountPlural(Лукерьи) DiscountPlural(Лукерьям) DiscountPlural(Лукерьями) DiscountPlural(Лукерьях) DiscountPlural(Лукреции) DiscountPlural(Лукреций) DiscountPlural(Лукрециям) DiscountPlural(Лукрециями) DiscountPlural(Лукрециях) DiscountPlural(Малании) DiscountPlural(Маланий) DiscountPlural(Маланиям) DiscountPlural(Маланиями) DiscountPlural(Маланиях) DiscountPlural(Маланьи) DiscountPlural(Маланьям) DiscountPlural(Маланьями) DiscountPlural(Маланьях) DiscountPlural(Марии) DiscountPlural(Марий) DiscountPlural(Мариям) DiscountPlural(Мариями) DiscountPlural(Мариях) DiscountPlural(Марьи) DiscountPlural(Марьям) DiscountPlural(Марьями) DiscountPlural(Марьях) DiscountPlural(матрон) DiscountPlural(матронам) DiscountPlural(матронами) DiscountPlural(матронах) DiscountPlural(матроны) DiscountPlural(Мелании) DiscountPlural(Меланий) DiscountPlural(Меланиям) DiscountPlural(Меланиями) DiscountPlural(Меланиях) DiscountPlural(Настасии) DiscountPlural(Настасий) DiscountPlural(Настасиям) DiscountPlural(Настасиями) DiscountPlural(Настасиях) DiscountPlural(Настасьи) DiscountPlural(Настасьям) DiscountPlural(Настасьями) DiscountPlural(Настасьях) DiscountPlural(Наталии) DiscountPlural(Наталий) DiscountPlural(Наталиям) DiscountPlural(Наталиями) DiscountPlural(Наталиях) DiscountPlural(Натальи) DiscountPlural(Натальям) DiscountPlural(Натальями) DiscountPlural(Натальях) DiscountPlural(Оливии) DiscountPlural(Оливий) DiscountPlural(Оливиям) DiscountPlural(Оливиями) DiscountPlural(Оливиях) DiscountPlural(Олимпии) DiscountPlural(Олимпий) DiscountPlural(Олимпиям) DiscountPlural(Олимпиями) DiscountPlural(Олимпиях) DiscountPlural(Поликсении) DiscountPlural(Поликсений) DiscountPlural(Поликсениям) DiscountPlural(Поликсениями) DiscountPlural(Поликсениях) DiscountPlural(Прасковий) DiscountPlural(Прасковьи) DiscountPlural(Прасковьям) DiscountPlural(Прасковьями) DiscountPlural(Прасковьях) DiscountPlural(Пульхерии) DiscountPlural(Пульхерий) DiscountPlural(Пульхериям) DiscountPlural(Пульхериями) DiscountPlural(Пульхериях) DiscountPlural(Розалии) DiscountPlural(Розалий) DiscountPlural(Розалиям) DiscountPlural(Розалиями) DiscountPlural(Розалиях) DiscountPlural(светкам) DiscountPlural(светками) DiscountPlural(светках) DiscountPlural(светки) DiscountPlural(светок) DiscountPlural(Сильвии) DiscountPlural(Сильвий) DiscountPlural(Сильвиям) DiscountPlural(Сильвиями) DiscountPlural(Сильвиях) DiscountPlural(Соломонии) DiscountPlural(Соломоний) DiscountPlural(Соломониям) DiscountPlural(Соломониями) DiscountPlural(Соломониях) DiscountPlural(Софии) DiscountPlural(Софий) DiscountPlural(Софиям) DiscountPlural(Софиями) DiscountPlural(Софиях) DiscountPlural(Стефании) DiscountPlural(Стефаний) DiscountPlural(Стефаниям) DiscountPlural(Стефаниями) DiscountPlural(Стефаниях) DiscountPlural(Таисии) DiscountPlural(Таисий) DiscountPlural(Таисиям) DiscountPlural(Таисиями) DiscountPlural(Таисиях) DiscountPlural(Таисьи) DiscountPlural(Таисьям) DiscountPlural(Таисьями) DiscountPlural(Таисьях) DiscountPlural(томкам) DiscountPlural(томками) DiscountPlural(томках) DiscountPlural(томки) DiscountPlural(томок) DiscountPlural(Устинии) DiscountPlural(Устиний) DiscountPlural(Устиниям) DiscountPlural(Устиниями) DiscountPlural(Устиниях) DiscountPlural(Устиньи) DiscountPlural(Устиньям) DiscountPlural(Устиньями) DiscountPlural(Устиньях) DiscountPlural(Февронии) DiscountPlural(Февроний) DiscountPlural(Феврониям) DiscountPlural(Феврониями) DiscountPlural(Феврониях) DiscountPlural(Февроньи) DiscountPlural(Февроньям) DiscountPlural(Февроньями) DiscountPlural(Февроньях) DiscountPlural(Федосии) DiscountPlural(Федосий) DiscountPlural(Федосиям) DiscountPlural(Федосиями) DiscountPlural(Федосиях) DiscountPlural(Федосьи) DiscountPlural(Федосьям) DiscountPlural(Федосьями) DiscountPlural(Федосьях) DiscountPlural(Федотии) DiscountPlural(Федотий) DiscountPlural(Федотиям) DiscountPlural(Федотиями) DiscountPlural(Федотиях) DiscountPlural(Федотьи) DiscountPlural(Федотьям) DiscountPlural(Федотьями) DiscountPlural(Федотьях) DiscountPlural(Фелиции) DiscountPlural(Фелиций) DiscountPlural(Фелициям) DiscountPlural(Фелициями) DiscountPlural(Фелициях) DiscountPlural(Феодосии) DiscountPlural(Феодосий) DiscountPlural(Феодосиям) DiscountPlural(Феодосиями) DiscountPlural(Феодосиях) DiscountPlural(Феодотии) DiscountPlural(Феодотий) DiscountPlural(Феодотиям) DiscountPlural(Феодотиями) DiscountPlural(Феодотиях) DiscountPlural(Феофании) DiscountPlural(Феофаний) DiscountPlural(Феофаниям) DiscountPlural(Феофаниями) DiscountPlural(Феофаниях) DiscountPlural(Фетинии) DiscountPlural(Фетиний) DiscountPlural(Фетиниям) DiscountPlural(Фетиниями) DiscountPlural(Фетиниях) DiscountPlural(Фетиньи) DiscountPlural(Фетиньям) DiscountPlural(Фетиньями) DiscountPlural(Фетиньях) DiscountPlural(Хавронии) DiscountPlural(Хавроний) DiscountPlural(Хаврониям) DiscountPlural(Хаврониями) DiscountPlural(Хаврониях) DiscountPlural(Цецилии) DiscountPlural(Цецилий) DiscountPlural(Цецилиям) DiscountPlural(Цецилиями) DiscountPlural(Цецилиях) DiscountPlural(Эмилии) DiscountPlural(Эмилий) DiscountPlural(Эмилиям) DiscountPlural(Эмилиями) DiscountPlural(Эмилиях) DiscountPlural(Юлиании) DiscountPlural(Юлианий) DiscountPlural(Юлианиям) DiscountPlural(Юлианиями) DiscountPlural(Юлианиях) DiscountPlural(Юлии) DiscountPlural(Юлий) DiscountPlural(Юлиям) DiscountPlural(Юлиями) DiscountPlural(Юлиях) /* подавляем формы множ. числа для существительных на -ОСТЬ и -ИЕ список форм получен из SQL словаря запросом: select distinct 'DiscountPlural('+F.name+')' from sg_entry E, sg_form F, sg_form_coord FC, sg_form_coord FC2 where E.id_class=9 and F.id_entry=E.id and FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1 and FC2.id_entry=E.id and FC2.iform=F.iform and FC2.icoord=24 and FC2.istate in (0,6) and (E.name like '%ИЕ' or E.name like '%ЬЕ' or E.name like '%ОСТЬ') */ DiscountPlural(абсолютизирования) DiscountPlural(абсолютизированья) DiscountPlural(абстрагирования) DiscountPlural(абстрагированья) DiscountPlural(авансирования) DiscountPlural(авансированья) DiscountPlural(авиапредприятия) DiscountPlural(авиапутешествия) DiscountPlural(авиасоединения) //DiscountPlural(автоколебания) //DiscountPlural(автопредприятия) //DiscountPlural(агропредприятия) DiscountPlural(активирования) DiscountPlural(активности) DiscountPlural(акционирования) DiscountPlural(анкетирования) DiscountPlural(аномальности) DiscountPlural(архиглупости) DiscountPlural(ассигнования) //DiscountPlural(ателье) //DiscountPlural(аудиосообщения) DiscountPlural(ауканья) DiscountPlural(аханья) DiscountPlural(бальзамирования) //DiscountPlural(банальности) DiscountPlural(бандподполья) //DiscountPlural(бандформирования) DiscountPlural(барахтания) DiscountPlural(бдения) //DiscountPlural(бедствия) DiscountPlural(бедствования) DiscountPlural(бездарности) DiscountPlural(беззакония) //DiscountPlural(безобразия) DiscountPlural(безумия) DiscountPlural(безумствования) DiscountPlural(беременности) DiscountPlural(бесконечности) DiscountPlural(бескрайности) DiscountPlural(бестактности) DiscountPlural(бесцеремонности) DiscountPlural(бибиканья) //DiscountPlural(биения) DiscountPlural(биоизлучения) DiscountPlural(биоизмерения) DiscountPlural(благовещения) DiscountPlural(благовещенья) DiscountPlural(благоволения) //DiscountPlural(благовония) //DiscountPlural(благовонья) DiscountPlural(благовремения) DiscountPlural(благовременья) DiscountPlural(благоглупости) DiscountPlural(благоговения) DiscountPlural(благоговенья) DiscountPlural(благодарения) DiscountPlural(благодарности) DiscountPlural(благодеяния) DiscountPlural(благодеянья) DiscountPlural(благозвучия) DiscountPlural(благозвучья) DiscountPlural(благолепия) DiscountPlural(благолепья) DiscountPlural(благоприличия) DiscountPlural(благоприличья) DiscountPlural(благородия) DiscountPlural(благородья) DiscountPlural(благословения) DiscountPlural(благословенья) DiscountPlural(благосостояния) DiscountPlural(благосостоянья) DiscountPlural(благости) DiscountPlural(благоухания) DiscountPlural(благоуханья) DiscountPlural(близости) //DiscountPlural(блуждания) //DiscountPlural(блужданья) DiscountPlural(богопочитания) DiscountPlural(богослужения) DiscountPlural(бодания) DiscountPlural(боестолкновения) DiscountPlural(болтания) DiscountPlural(бомбометания) DiscountPlural(бормотания) DiscountPlural(бормотанья) DiscountPlural(боронования) DiscountPlural(боронованья) DiscountPlural(бравирования) DiscountPlural(бравированья) DiscountPlural(бракосочетания) DiscountPlural(бракосочетанья) DiscountPlural(братания) DiscountPlural(братанья) DiscountPlural(брожения) DiscountPlural(броженья) DiscountPlural(бросания) DiscountPlural(брыкания) DiscountPlural(брыканья) DiscountPlural(брюзжания) DiscountPlural(брюзжанья) //DiscountPlural(буквосочетания) DiscountPlural(бурления) DiscountPlural(бурленья) DiscountPlural(бурчания) DiscountPlural(бурчанья) DiscountPlural(бухтения) DiscountPlural(бытописания) DiscountPlural(бытописанья) DiscountPlural(валентности) DiscountPlural(валяния) DiscountPlural(варенья) DiscountPlural(ваяния) DiscountPlural(вбивания) DiscountPlural(вбирания) DiscountPlural(вбрасывания) DiscountPlural(вбухивания) DiscountPlural(вваливания) DiscountPlural(введения) DiscountPlural(ввертывания) DiscountPlural(ввертыванья) DiscountPlural(ввинчивания) DiscountPlural(ввинчиванья) DiscountPlural(вгрызания) DiscountPlural(вдавливания) DiscountPlural(вдевания) DiscountPlural(вдергивания) DiscountPlural(вдохновения) DiscountPlural(вдохновенья) DiscountPlural(вдувания) DiscountPlural(ведомости) DiscountPlural(вежливости) DiscountPlural(везения) DiscountPlural(везенья) DiscountPlural(веления) DiscountPlural(венеротрясения) DiscountPlural(венчания) DiscountPlural(венчанья) //DiscountPlural(верования) DiscountPlural(вероисповедания) //DiscountPlural(вероучения) //DiscountPlural(вероученья) DiscountPlural(вероятности) //DiscountPlural(верховья) //DiscountPlural(ветвления) //DiscountPlural(ветвленья) DiscountPlural(ветшания) DiscountPlural(вечности) DiscountPlural(вещания) //DiscountPlural(веяния) DiscountPlural(вживления) DiscountPlural(взаимовлияния) DiscountPlural(взаимодействия) //DiscountPlural(взаимозависимости) //DiscountPlural(взаимоотношения) DiscountPlural(взаимоположения) DiscountPlural(взаимопревращения) DiscountPlural(взаимопроникновения) DiscountPlural(взбивания) DiscountPlural(взбрыкивания) DiscountPlural(взбухания) DiscountPlural(взвевания) DiscountPlural(взвешивания) DiscountPlural(взвизгивания) DiscountPlural(взвывания) DiscountPlural(взгорья) DiscountPlural(взгромождения) DiscountPlural(вздевания) DiscountPlural(вздрагивания) DiscountPlural(вздувания) DiscountPlural(вздутия) DiscountPlural(вздыбливания) DiscountPlural(вздымания) DiscountPlural(взлаивания) DiscountPlural(взмахивания) DiscountPlural(взмывания) DiscountPlural(взыскания) DiscountPlural(взятия) //DiscountPlural(видения) //DiscountPlural(виденья) DiscountPlural(видеоизображения) DiscountPlural(видеонаблюдения) //DiscountPlural(видеопослания) DiscountPlural(видеоприложения) DiscountPlural(видимости) DiscountPlural(видоизменения) DiscountPlural(визжания) DiscountPlural(визжанья) DiscountPlural(виляния) DiscountPlural(висения) DiscountPlural(вихляния) DiscountPlural(вклинивания) DiscountPlural(включения) DiscountPlural(вкрапления) DiscountPlural(вкручивания) DiscountPlural(вкусности) DiscountPlural(владения) DiscountPlural(влезания) DiscountPlural(влечения) //DiscountPlural(вливания) //DiscountPlural(влияния) //DiscountPlural(вложения) DiscountPlural(влюбленности) DiscountPlural(внедрения) DiscountPlural(внезапности) DiscountPlural(внесения) DiscountPlural(внешности) //DiscountPlural(внутренности) DiscountPlural(внушения) DiscountPlural(водопользования) DiscountPlural(водопользованья) DiscountPlural(водружения) DiscountPlural(вожделения) DiscountPlural(вожделенья) DiscountPlural(возвращения) DiscountPlural(возвышения) DiscountPlural(возвышенности) DiscountPlural(возгорания) DiscountPlural(воздаяния) //DiscountPlural(воздействия) //DiscountPlural(воззвания) //DiscountPlural(воззрения) //DiscountPlural(возлияния) DiscountPlural(возмездия) DiscountPlural(возможности) DiscountPlural(возмущения) DiscountPlural(вознаграждения) //DiscountPlural(возражения) DiscountPlural(волеизъявления) //DiscountPlural(волнения) DiscountPlural(волненья) DiscountPlural(волости) DiscountPlural(вольности) DiscountPlural(вооружения) DiscountPlural(воплощения) DiscountPlural(воплощенья) //DiscountPlural(восклицания) DiscountPlural(воскресения) DiscountPlural(воскресенья) DiscountPlural(воскрешения) DiscountPlural(воспаления) DiscountPlural(воспевания) //DiscountPlural(воспоминания) //DiscountPlural(воспоминанья) DiscountPlural(восприятия) DiscountPlural(воспроизведения) DiscountPlural(восславления) DiscountPlural(воссоединения) //DiscountPlural(восстания) DiscountPlural(восстановления) DiscountPlural(восхваления) DiscountPlural(восхищения) DiscountPlural(восхождения) DiscountPlural(восьмидесятилетия) DiscountPlural(восьмистишия) //DiscountPlural(впечатления) //DiscountPlural(впечатленья) DiscountPlural(впрыскивания) DiscountPlural(времяисчисления) DiscountPlural(вручения) DiscountPlural(вселения) DiscountPlural(вскрикивания) DiscountPlural(вскрытия) DiscountPlural(всплытия) DiscountPlural(вспрыгивания) DiscountPlural(вспухания) DiscountPlural(вспучивания) DiscountPlural(вспушивания) DiscountPlural(вставления) DiscountPlural(встревания) DiscountPlural(встряхивания) DiscountPlural(вступления) DiscountPlural(всучивания) DiscountPlural(всхлипывания) DiscountPlural(всхрапывания) DiscountPlural(всыпания) DiscountPlural(вталкивания) DiscountPlural(втирания) DiscountPlural(вторжения) DiscountPlural(втравливания) DiscountPlural(вульгарности) //DiscountPlural(вхождения) DiscountPlural(выбывания) DiscountPlural(выбытия) DiscountPlural(выведывания) DiscountPlural(выдвижения) DiscountPlural(выделения) DiscountPlural(выделывания) DiscountPlural(выдумывания) DiscountPlural(выздоравливания) DiscountPlural(выискивания) DiscountPlural(выказывания) DiscountPlural(выключения) DiscountPlural(выковывания) DiscountPlural(выкорчевывания) DiscountPlural(выкручивания) DiscountPlural(вылечивания) DiscountPlural(выпадения) DiscountPlural(выпекания) DiscountPlural(выполнения) DiscountPlural(выпрастывания) //DiscountPlural(выпуклости) DiscountPlural(выравнивания) //DiscountPlural(выражения) //DiscountPlural(выраженья) DiscountPlural(высвистывания) DiscountPlural(выселения) DiscountPlural(высечения) //DiscountPlural(высказывания) DiscountPlural(высокоблагородия) DiscountPlural(высокогорья) DiscountPlural(выстуживания) DiscountPlural(выступления) //DiscountPlural(высыпания) DiscountPlural(вычеркивания) //DiscountPlural(вычисления) DiscountPlural(вычитания) DiscountPlural(вычитывания) DiscountPlural(вышагивания) DiscountPlural(вышивания) DiscountPlural(вышучивания) DiscountPlural(выявления) DiscountPlural(выяснения) DiscountPlural(вяканья) DiscountPlural(гадания) //DiscountPlural(гадости) DiscountPlural(гашения) //DiscountPlural(гидросооружения) //DiscountPlural(гиперплоскости) DiscountPlural(гипноизлучения) DiscountPlural(главнокомандования) DiscountPlural(глиссирования) DiscountPlural(глиссированья) DiscountPlural(глумления) DiscountPlural(глумленья) //DiscountPlural(глупости) DiscountPlural(гнездования) DiscountPlural(гнездованья) //DiscountPlural(гнездовья) DiscountPlural(гноения) //DiscountPlural(гнусности) DiscountPlural(говенья) DiscountPlural(головокружения) DiscountPlural(головокруженья) DiscountPlural(голосования) //DiscountPlural(гонения) //DiscountPlural(госпредприятия) DiscountPlural(госсобственности) //DiscountPlural(гостей) //DiscountPlural(гости) //DiscountPlural(госучреждения) DiscountPlural(грехопадения) DiscountPlural(грубости) DiscountPlural(группирования) //DiscountPlural(гуляния) //DiscountPlural(гулянья) DiscountPlural(давления) DiscountPlural(давности) DiscountPlural(дактилоскопирования) DiscountPlural(данности) DiscountPlural(дарения) DiscountPlural(дарования) DiscountPlural(датирования) DiscountPlural(двенадцатилетия) //DiscountPlural(движения) //DiscountPlural(движенья) DiscountPlural(двоеточия) //DiscountPlural(двусмысленности) //DiscountPlural(двустишия) DiscountPlural(двухсотлетия) DiscountPlural(девяностолетия) DiscountPlural(деепричастия) //DiscountPlural(действия) DiscountPlural(деления) DiscountPlural(деликатности) DiscountPlural(демонстрирования) DiscountPlural(дергания) DiscountPlural(дерганья) DiscountPlural(держания) DiscountPlural(дерзания) DiscountPlural(дерзновения) DiscountPlural(дерзости) DiscountPlural(десятиборья) DiscountPlural(десятилетия) //DiscountPlural(деяния) //DiscountPlural(деянья) DiscountPlural(деятельности) // являются высшим критерием и конечной целью профессиональной деятельности госслужащего DiscountPlural(диагностирования) DiscountPlural(дикости) //DiscountPlural(дипотношения) DiscountPlural(добавления) DiscountPlural(добродетельности) //DiscountPlural(доверенности) DiscountPlural(доворачивания) DiscountPlural(договоренности) DiscountPlural(дозволения) DiscountPlural(долечивания) //DiscountPlural(должности) //DiscountPlural(домовладения) DiscountPlural(домоправления) //DiscountPlural(домостроения) DiscountPlural(домоуправления) DiscountPlural(домысливания) DiscountPlural(донесения) DiscountPlural(доперечисления) DiscountPlural(дописывания) //DiscountPlural(дополнения) DiscountPlural(допрашивания) //DiscountPlural(допущения) DiscountPlural(доставания) DiscountPlural(доставления) //DiscountPlural(достижения) DiscountPlural(достоверности) DiscountPlural(достопамятности) DiscountPlural(достояния) //DiscountPlural(досье) DiscountPlural(дотрагивания) DiscountPlural(доукомплектования) //DiscountPlural(драгоценности) //DiscountPlural(древности) //DiscountPlural(дрыганья) DiscountPlural(дудения) //DiscountPlural(дуновения) DiscountPlural(дуракаваляния) DiscountPlural(дурновкусия) DiscountPlural(дурости) DiscountPlural(единообразия) DiscountPlural(еканья) //DiscountPlural(емкости) DiscountPlural(ерзанья) DiscountPlural(жалования) DiscountPlural(жалованья) //DiscountPlural(желания) //DiscountPlural(желанья) DiscountPlural(жертвоприношения) DiscountPlural(жестокости) DiscountPlural(живописания) DiscountPlural(живописанья) //DiscountPlural(жидкости) DiscountPlural(жизнеописания) DiscountPlural(жизнепонимания) //DiscountPlural(жития) DiscountPlural(жонглирования) DiscountPlural(жонглированья) //DiscountPlural(заблуждения) //DiscountPlural(заблужденья) //DiscountPlural(заболевания) //DiscountPlural(заведения) //DiscountPlural(заведенья) //DiscountPlural(заверения) DiscountPlural(завершения) DiscountPlural(завещания) DiscountPlural(завещанья) DiscountPlural(зависания) //DiscountPlural(зависимости) //DiscountPlural(завихрения) //DiscountPlural(завоевания) //DiscountPlural(завывания) //DiscountPlural(завыванья) DiscountPlural(завышения) DiscountPlural(заглавия) DiscountPlural(заглубления) DiscountPlural(заглушения) DiscountPlural(заграждения) DiscountPlural(загромождения) DiscountPlural(загрубения) DiscountPlural(загрязнения) DiscountPlural(загрязненности) DiscountPlural(загустевания) //DiscountPlural(задания) DiscountPlural(задержания) DiscountPlural(задолженности) DiscountPlural(задымления) DiscountPlural(зажатия) DiscountPlural(зажатости) DiscountPlural(зазрения) DiscountPlural(зазывания) DiscountPlural(заигрывания) DiscountPlural(заикания) //DiscountPlural(заимствования) DiscountPlural(закаливания) //DiscountPlural(заклинания) //DiscountPlural(заклинанья) DiscountPlural(заключения) //DiscountPlural(заклятия) //DiscountPlural(заклятья) //DiscountPlural(закономерности) DiscountPlural(законопослушания) DiscountPlural(закрашивания) //DiscountPlural(закругления) //DiscountPlural(закругленности) DiscountPlural(закручивания) DiscountPlural(закрытия) DiscountPlural(заксобрания) DiscountPlural(залегания) DiscountPlural(заледенения) DiscountPlural(залития) //DiscountPlural(замечания) DiscountPlural(замирения) //DiscountPlural(замыкания) DiscountPlural(замысловатости) DiscountPlural(замятия) DiscountPlural(занижения) DiscountPlural(занимания) //DiscountPlural(занятия) //DiscountPlural(занятья) DiscountPlural(западания) DiscountPlural(западения) DiscountPlural(запаздывания) DiscountPlural(заполнения) DiscountPlural(заполняемости) DiscountPlural(запугивания) DiscountPlural(запутанности) //DiscountPlural(запястья) DiscountPlural(заседания) DiscountPlural(засорения) DiscountPlural(застолья) DiscountPlural(застревания) DiscountPlural(затмения) DiscountPlural(заточения) //DiscountPlural(затруднения) DiscountPlural(затушевывания) DiscountPlural(заумности) DiscountPlural(захватывания) DiscountPlural(захмеления) DiscountPlural(захолустья) DiscountPlural(зацикливания) DiscountPlural(зачатия) DiscountPlural(зачерствения) DiscountPlural(зачисления) //DiscountPlural(заявления) //DiscountPlural(звания) DiscountPlural(званья) DiscountPlural(звукоподражания) DiscountPlural(звукосочетания) //DiscountPlural(здания) DiscountPlural(здоровья) DiscountPlural(зелья) DiscountPlural(землевладения) DiscountPlural(землетрясения) //DiscountPlural(зимовья) DiscountPlural(зияния) //DiscountPlural(злодеяния) //DiscountPlural(злоключения) //DiscountPlural(злоупотребления) //DiscountPlural(знаменитости) //DiscountPlural(знамения) //DiscountPlural(знаменья) //DiscountPlural(знания) //DiscountPlural(значения) //DiscountPlural(значенья) DiscountPlural(значимости) DiscountPlural(избавленья) DiscountPlural(избивания) DiscountPlural(избиения) DiscountPlural(избрания) //DiscountPlural(изваяния) //DiscountPlural(изваянья) DiscountPlural(изведения) //DiscountPlural(извержения) //DiscountPlural(известия) //DiscountPlural(извещения) //DiscountPlural(извинения) DiscountPlural(извлечения) DiscountPlural(изволения) //DiscountPlural(извращения) DiscountPlural(изгнания) DiscountPlural(изгнанья) DiscountPlural(изголовья) //DiscountPlural(издания) //DiscountPlural(изделия) DiscountPlural(излития) DiscountPlural(излияния) DiscountPlural(изложения) DiscountPlural(излучения) DiscountPlural(изменения) DiscountPlural(измерения) DiscountPlural(измышления) //DiscountPlural(изнасилования) DiscountPlural(изобличения) //DiscountPlural(изображения) //DiscountPlural(изобретения) //DiscountPlural(изречения) DiscountPlural(изъявления) DiscountPlural(изъязвления) //DiscountPlural(изъятия) DiscountPlural(изысканности) DiscountPlural(изящности) DiscountPlural(иконопочитания) DiscountPlural(именитости) //DiscountPlural(имения) //DiscountPlural(именья) DiscountPlural(имитирования) DiscountPlural(индивидуальности) DiscountPlural(индуктивности) DiscountPlural(инкассирования) DiscountPlural(иносказания) DiscountPlural(интимности) DiscountPlural(инцидентности) //DiscountPlural(искажения) //DiscountPlural(искания) //DiscountPlural(исключения) DiscountPlural(искрения) //DiscountPlural(искривления) DiscountPlural(искушения) //DiscountPlural(испарения) DiscountPlural(исповедания) DiscountPlural(испоганивания) //DiscountPlural(исправления) //DiscountPlural(испражнения) //DiscountPlural(испытания) DiscountPlural(иссечения) //DiscountPlural(исследования) DiscountPlural(Универсиады)
затон затону --> затонуть затону
wordform_score "затону" { существительное } = -1
7,303,783
[ 1, 145, 120, 145, 113, 146, 229, 145, 127, 145, 126, 225, 145, 120, 145, 113, 146, 229, 145, 127, 145, 126, 146, 230, 15431, 225, 145, 120, 145, 113, 146, 229, 145, 127, 145, 126, 146, 230, 146, 229, 146, 239, 225, 145, 120, 145, 113, 146, 229, 145, 127, 145, 126, 146, 230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2076, 687, 67, 6355, 315, 145, 120, 145, 113, 146, 229, 145, 127, 145, 126, 146, 230, 6, 288, 225, 146, 228, 146, 230, 146, 236, 145, 118, 146, 228, 146, 229, 145, 115, 145, 121, 146, 229, 145, 118, 145, 124, 146, 239, 145, 126, 145, 127, 145, 118, 289, 273, 300, 21, 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 ]
pragma solidity 0.6.12; // SPDX-License-Identifier: MIT import '@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol'; import "./ArtichainToken.sol"; interface IMigratorArt { // Perform LP token migration from legacy PancakeSwap to ArtichainSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to PancakeSwap LP tokens. // ArtichainSwap must mint EXACTLY the same amount of PancakeSwap LP tokens or // else something bad will happen. Traditional PancakeSwap does not // do that so be careful! function migrate(IBEP20 token) external returns (IBEP20); } // MasterArt is the master of Ait. He can make Ait and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once AIT is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterArt is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of AITs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accAitPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accAitPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. AITs to distribute per block. uint256 lastRewardBlock; // Last block number that AITs distribution occurs. uint256 accAitPerShare; // Accumulated AITs per share, times 1e12. See below. uint16 depositFee; // Deposit fee in basis points } // Block reward plan struct BlockRewardInfo { uint256 firstBlock; // First block number uint256 lastBlock; // Last block number uint256 reward; // Block reward amount } // The Artichain TOKEN! ArtichainToken public ait; // Dev address. address public devAddr; // Fee address address public feeAddr; // Bonus muliplier for early ait makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorArt public migrator; // Info of each pool. PoolInfo[] public poolInfo; BlockRewardInfo[] public rewardInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when AIT mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetFeeAddress(address indexed user, address indexed newAddress); event SetDevAddress(address indexed user, address indexed newAddress); constructor( ArtichainToken _ait, address _devAddr, address _feeAddr, uint256 _startBlock ) public { ait = _ait; devAddr = _devAddr; feeAddr = _feeAddr; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _ait, allocPoint: 1000, lastRewardBlock: startBlock, accAitPerShare: 0, depositFee: 0 })); setRewardInfo(); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) external onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFee, bool _withUpdate) external onlyOwner { require(_depositFee <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accAitPerShare: 0, depositFee: _depositFee })); updateStakingPool(); } // Update the given pool's AIT allocation point and deposit fee. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFee, bool _withUpdate) external onlyOwner { require(_depositFee <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFee = _depositFee; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. // function setMigrator(IMigratorArt _migrator) external onlyOwner { // migrator = _migrator; // } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. // function migrate(uint256 _pid) external { // require(address(migrator) != address(0), "migrate: no migrator"); // PoolInfo storage pool = poolInfo[_pid]; // IBEP20 lpToken = pool.lpToken; // uint256 bal = lpToken.balanceOf(address(this)); // lpToken.safeApprove(address(migrator), bal); // IBEP20 newLpToken = migrator.migrate(lpToken); // require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); // pool.lpToken = newLpToken; // } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // Returns reward for each block function getBlockReward() external view returns (uint256) { if(block.number < startBlock) return 0; for(uint i = 0; i < 3; i++) { if(block.number <= rewardInfo[i].lastBlock) { return rewardInfo[i].reward; } } return 0; } // Update reward table for 3 years // first year reward: 4000 // second year reward: 2000 // third year reward: 1000 function setRewardInfo() internal { if(rewardInfo.length == 0) { uint256 supply = 4000; for(uint i = 0; i < 3; i++) { uint256 perBlockReward = supply.mul(3 * 1e18).mul(100).div(110).div(365 days); rewardInfo.push(BlockRewardInfo({firstBlock: 0, lastBlock: 0, reward: perBlockReward})); supply = supply.div(2); } } uint256 _firstBlock = startBlock; for(uint i = 0; i < 3; i++) { rewardInfo[i].firstBlock = _firstBlock; rewardInfo[i].lastBlock = _firstBlock + (365 days) / 3; _firstBlock = _firstBlock + (365 days) / 3 + 1; } } function calcPoolReward(uint256 _pid) internal view returns (uint256){ PoolInfo storage pool = poolInfo[_pid]; if(block.number < startBlock) return 0; uint256 aitReward = 0; uint256 lastBlock = pool.lastRewardBlock; for(uint i = 0; i < 3; i++) { if(pool.lastRewardBlock > rewardInfo[i].lastBlock) continue; if(block.number <= rewardInfo[i].lastBlock) { uint256 multiplier = getMultiplier(lastBlock, block.number); uint256 _reward = multiplier.mul(rewardInfo[i].reward); aitReward = aitReward.add(_reward); break; } else { uint256 multiplier = getMultiplier(lastBlock, rewardInfo[i].lastBlock); uint256 _reward = multiplier.mul(rewardInfo[i].reward); aitReward = aitReward.add(_reward); } lastBlock = rewardInfo[i].lastBlock; } return aitReward.mul(pool.allocPoint).div(totalAllocPoint); } // View function to see pending AITs on frontend. function pendingAit(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAitPerShare = pool.accAitPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 aitReward = calcPoolReward(_pid); accAitPerShare = accAitPerShare.add(aitReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAitPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 aitReward = calcPoolReward(_pid); ait.mint(devAddr, aitReward.div(10)); // 10% is dev reward ait.mint(address(this), aitReward); pool.accAitPerShare = pool.accAitPerShare.add(aitReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterArt for AIT allocation. function deposit(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAitPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAitTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFee > 0) { uint256 depositFee = _amount.mul(pool.depositFee).div(10000); pool.lpToken.safeTransfer(feeAddr, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); } else { user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accAitPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterArt. function withdraw(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accAitPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAitTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accAitPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe ait transfer function, just in case if rounding error causes pool to not have enough AITs. function safeAitTransfer(address _to, uint256 _amount) internal { uint256 aitBal = ait.balanceOf(address(this)); bool transferSuccess = false; if (_amount > aitBal) { transferSuccess = ait.transfer(_to, aitBal); } else { transferSuccess = ait.transfer(_to, _amount); } require(transferSuccess, "safeAitTransfer: transfer failed"); } // Update dev address by the previous dev. function dev(address _devAddr) external { require(msg.sender == devAddr, "dev: wut?"); devAddr = _devAddr; emit SetDevAddress(msg.sender, _devAddr); } // Update fee address by the previous fee manager. function setFeeAddress(address _feeAddr) external { require(msg.sender == feeAddr, "setFeeAddress: Forbidden"); feeAddr = _feeAddr; emit SetFeeAddress(msg.sender, _feeAddr); } function updateStartBlock(uint256 _startBlock) external onlyOwner { require(block.number < startBlock, "Staking was started already"); require(block.number < _startBlock); startBlock = _startBlock; setRewardInfo(); } }
Update the given pool's AIT allocation point and deposit fee. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFee, bool _withUpdate) external onlyOwner { require(_depositFee <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFee = _depositFee; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } }
12,854,180
[ 1, 1891, 326, 864, 2845, 1807, 432, 1285, 13481, 1634, 471, 443, 1724, 14036, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 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, 565, 445, 444, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 9853, 2148, 16, 2254, 2313, 389, 323, 1724, 14667, 16, 1426, 389, 1918, 1891, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 323, 1724, 14667, 1648, 12619, 16, 315, 542, 30, 2057, 443, 1724, 14036, 10853, 3143, 8863, 203, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 2807, 8763, 2148, 273, 2845, 966, 63, 67, 6610, 8009, 9853, 2148, 31, 203, 3639, 2845, 966, 63, 67, 6610, 8009, 9853, 2148, 273, 389, 9853, 2148, 31, 203, 3639, 2845, 966, 63, 67, 6610, 8009, 323, 1724, 14667, 273, 389, 323, 1724, 14667, 31, 203, 3639, 309, 261, 10001, 8763, 2148, 480, 389, 9853, 2148, 13, 288, 203, 5411, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1717, 12, 10001, 8763, 2148, 2934, 1289, 24899, 9853, 2148, 1769, 203, 5411, 1089, 510, 6159, 2864, 5621, 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 ]
contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract ParentToken { /* library used for calculations */ using SafeMath for uint256; /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address=>uint)) allowance; /* Initializes contract with initial supply tokens to the creator of the contract */ function ParentToken(uint256 currentSupply, string tokenName, uint8 decimalUnits, string tokenSymbol){ balances[msg.sender] = currentSupply; // Give the creator all initial tokens totalSupply = currentSupply; // Update total supply name = tokenName; // Set the name for display purposes decimals = decimalUnits; // Decimals for the tokens symbol = tokenSymbol; // Set the symbol for display purposes } ///@notice Transfer tokens to the beneficiary account ///@param to The beneficiary account ///@param value The amount of tokens to be transfered function transfer(address to, uint value) returns (bool success){ require( balances[msg.sender] >= value && value > 0 ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); return true; } ///@notice Allow another contract to spend some tokens in your behalf ///@param spender The address authorized to spend ///@param value The amount to be approved function approve(address spender, uint256 value) returns (bool success) { allowance[msg.sender][spender] = value; return true; } ///@notice Approve and then communicate the approved contract in a single tx ///@param spender The address authorized to spend ///@param value The amount to be approved function approveAndCall(address spender, uint256 value, bytes extraData) returns (bool success) { tokenRecipient recSpender = tokenRecipient(spender); if (approve(spender, value)) { recSpender.receiveApproval(msg.sender, value, this, extraData); return true; } } ///@notice Transfer tokens between accounts ///@param from The benefactor/sender account. ///@param to The beneficiary account ///@param value The amount to be transfered function transferFrom(address from, address to, uint value) returns (bool success){ require( allowance[from][msg.sender] >= value &&balances[from] >= value && value > 0 ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); return true; } } library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract MLC is owned,ParentToken{ /* library used for calculations */ using SafeMath for uint256; /* Public variables of the token */ string public standard = 'Token 0.1'; uint256 public currentSupply= 2400000000000000; string public constant symbol = "MLC"; string public constant tokenName = "Melania"; uint8 public constant decimals = 8; mapping (address => bool) public frozenAccount; ///@notice Default function used for any payments made. function () payable { acceptPayment(); } ///@notice Accept payment and transfer to owner account. function acceptPayment() payable { require(msg.value>0); owner.transfer(msg.value); } function MLC()ParentToken(currentSupply,tokenName,decimals,symbol){} ///@notice Provides balance of the account requested ///@param add Address of the account for which balance is being enquired function balanceOf(address add) constant returns (uint balance){ return balances[add]; } ///@notice Transfer tokens to the beneficiary account ///@param to The beneficiary account ///@param value The amount of tokens to be transfered function transfer(address to, uint value) returns (bool success){ require( balances[msg.sender] >= value && value > 0 && (!frozenAccount[msg.sender]) // Allow transfer only if account is not frozen ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); // Update the balance of beneficiary account Transfer(msg.sender,to,value); return true; } ///@notice Transfer tokens between accounts ///@param from The benefactor/sender account. ///@param to The beneficiary account ///@param value The amount to be transfered function transferFrom(address from, address to, uint value) returns (bool success){ require( allowance[from][msg.sender] >= value &&balances[from] >= value //Check if the benefactor has sufficient balance && value > 0 && (!frozenAccount[msg.sender]) // Allow transfer only if account is not frozen ); balances[from] = balances[from].sub(value); // Deduct from the benefactor account balances[to] = balances[to].add(value); // Update the balance of beneficiary account allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); Transfer(from,to,value); return true; } ///@notice Increase the number of coins ///@param target The address of the account where the coins would be added. ///@param mintedAmount The amount of coins to be added function mintToken(address target, uint256 mintedAmount) onlyOwner { balances[target] = balances[target].add(mintedAmount); //Add the amount of coins to be increased to the balance currentSupply = currentSupply.add(mintedAmount); //Add the amount of coins to be increased to the supply Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } ///@notice Freeze the account at the target address ///@param target The address of the account to be frozen function freezeAccount(address target, bool freeze) onlyOwner { require(freeze); //Check if account has to be freezed frozenAccount[target] = freeze; //Freeze the account FrozenFunds(target, freeze); } /// @notice Remove tokens from the system irreversibly /// @param value The amount of money to burn function burn(uint256 value) returns (bool success) { require (balances[msg.sender] > value && value>0); // Check if the sender has enough balance balances[msg.sender] = balances[msg.sender].sub(value); // Deduct from the sender currentSupply = currentSupply.sub(value); // Update currentSupply Burn(msg.sender, value); return true; } function burnFrom(address from, uint256 value) returns (bool success) { require(balances[from] >= value); // Check if the targeted balance is enough require(value <= allowance[from][msg.sender]); // Check allowance balances[from] = balances[from].sub(value); // Deduct from the targeted balance allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); // Deduct from the sender's allowance currentSupply = currentSupply.sub(value); // Update currentSupply Burn(from, value); return true; } /* This notifies clients about the amount transfered */ event Transfer(address indexed _from, address indexed _to,uint256 _value); /* This notifies clients about the amount approved */ event Approval(address indexed _owner, address indexed _spender,uint256 _value); /* This notifies clients about the account freeze */ event FrozenFunds(address target, bool frozen); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); }
Update the balance of beneficiary account
balances[to] = balances[to].add(value);
4,805,681
[ 1, 1891, 326, 11013, 434, 27641, 74, 14463, 814, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 324, 26488, 63, 869, 65, 273, 225, 324, 26488, 63, 869, 8009, 1289, 12, 1132, 1769, 4766, 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 ]
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/evm-contracts/src/v0.6/ChainlinkClient.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/math/SafeMath.sol"; // to do: add events, test everything, chainlink integration // interface of contract factory to trigger payout interface iICFactory { function payout(bool) external; } // ERC 20 interface for LINK token interface iERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } // Insurance Contract contract Insurance is ChainlinkClient { using SafeMath for uint256; address CL_NODE = 0xc47e0FBdf1d71Dfe58cD403A582916A52E3d707f; // Chainlink node address address private LINK_ADDRESS = 0xa36085F69e2889c224210F603D836748e7dC0088; // kovan LINK token address iERC20 link = iERC20(LINK_ADDRESS); // link token contract instance address private oracle = 0xB84be727Ff04B64D5f85e0a669Af0ef8e14f530B; // exm oracle address uint256 private fee = 0.1 * 10 ** 18; // 0.1 LINK address payable public creator; // creator of the insurance (farmer) address payable public icFactory; // address of the insurance factory string public location; // weather adapter station uint256 public crop; // ensured crop in Wei uint256 public weatherCondition; // ensured weather condition uint256 public weatherConMin; // weather condition threshold min uint256 public weatherConMax; // weather condition threshold max uint256 public creationDate; // date of contract creation uint256 public endDate; // end date of insurance uint256 public threshold; // threshold of weather condition bool public isActive; // true = insurance is active, false = insurance isn't active iICFactory public factory; // contract instance of insurance factory struct RequestData { // stores history values of requested data uint256 date; uint256 value; } struct Job { // stores job informations string name; bytes32 jobId; string source; } RequestData[] public requestHistory; // list of weather data history Job[] private jobIds; // list of products/jobs uint256 public counter; // counts chainlink requests uint256 public tempResult; // temporary chianlink result for average calculation // modifier for function which can only called by factory contract modifier onlyIcFactory() { require(msg.sender == icFactory, 'msg.sender is not allowed'); _; } // modifier for functions that can only called by exm chainlink node modifier onlyCLNode() { require(msg.sender == CL_NODE, 'msg.sender is not allowed'); _; } constructor ( address payable creator_, // address of insurance creator string memory location_, // location of weather station uint256 crop_, // ensured crop in Wei uint256 weatherCondition_, // wensured eather condition uint256 durationMonth_, // month of the insurance period uint256 threshold_ ) public { // threshold of weather condition setPublicChainlinkToken(); // sets chainlink token address creator = creator_; icFactory = payable(msg.sender); location = location_; crop = crop_; weatherCondition = weatherCondition_; // input value * 100. --> instead of 42.42 degree input should be 4242 endDate = block.timestamp.add(durationMonth_.mul(4 weeks)); // sets end date of insurance creationDate = block.timestamp; threshold = threshold_; factory = iICFactory(icFactory); // insurance contract factory instance counter = 0; // sets the chainlink job counter to zero isActive = true; // activates the contract // weatherConMin, weatherConMax // values at which the insurance takes effect uint256 weatherConDiff = (weatherCondition.mul(threshold)).div(100); weatherConMin = weatherCondition.sub(weatherConDiff); weatherConMax = weatherCondition.add(weatherConDiff); } function getIsActive() external view returns(bool) { return isActive; } function getCreator() external view returns(address) { return creator; } // checks if the current weather value is greater than or less than the specified threshold function isInsuranceCase(uint256 latestValue) internal view returns(bool) { return (latestValue > weatherConMax || latestValue < weatherConMin); } // checks that the contract period has not yet been exceeded. function isPeriod() internal view returns(bool) { return (endDate >= block.timestamp); } // ends the insurance contract // @param insuranceCase true if insurance case, false if no insurance case function endContract(bool insuranceCase) internal { isActive = false; payBackLink(); factory.payout(insuranceCase); } // for paying back link to insurance factory after contract ends function payBackLink() internal { link.transfer(icFactory, link.balanceOf(address(this))); } // request weather data // executes Chainlink jobs function sendRequest() external onlyIcFactory { requestHistory.push(RequestData(block.timestamp, 0)); // saves date of request to history counter = 0; tempResult = 0; // sends a chainlink request for every job in list for(uint256 i; i<jobIds.length; i++) { // new chainlink request Chainlink.Request memory req = buildChainlinkRequest(jobIds[i].jobId, address(this), this.checkInsuranceCase.selector); // adding location to request, if requested adapter is openweathermap adapter if(keccak256(abi.encodePacked(jobIds[i].source )) == keccak256(abi.encodePacked('owm'))) req.add("city", location); // adding 'swbb5d' geohash to request, if requested adapter is exm adapter if(keccak256(abi.encodePacked(jobIds[i].source )) == keccak256(abi.encodePacked('exm'))) req.add('geohash', 'swbb5d'); //sends chainlink request sendChainlinkRequestTo(oracle, req, fee); } } // add a new chainlink job to contract // can only called by insurance contract factory (while contract creation) function addJob(string calldata name, bytes32 jobId, string calldata source) external onlyIcFactory { jobIds.push(Job(name, jobId, source)); } // Checks whether an insured event has occurred or the term has been exceeded. // If the term is exceeded, the factory contract gets its funds back. // If an insured event occurs, the creator of the contract receives the insured amount. function checkInsuranceCase(bytes32 _requestId, uint256 externalValue) public recordChainlinkFulfillment(_requestId) { require(isActive, 'contract is no longer active'); // counts the number of chainlink request results counter++; // adding all results to temporary result tempResult += externalValue; if(counter==jobIds.length) { // calculate the average uint256 average = tempResult.div(jobIds.length); // add average of latest values to history requestHistory[requestHistory.length-1].value = average; // checks insurance conditions if(isPeriod()) { if(isInsuranceCase(average)) { endContract(true); // its an insurance case } } else { endContract(false); // insurance period is over, it is no insurance case } } } function getCrop() external view returns (uint256) { return crop; } // returns state values function getAllContractData() public view returns(address payable, // creator address payable, // icFactory Job[] memory, // jobIds string memory, // location uint256, // crop uint256, // endDate uint256, // creation date uint256, // threshold uint256, // weatherCondition uint256, // weatherConMax uint256, // weatherConMin bool, // isActive RequestData[] memory) { return(creator, icFactory, jobIds, location, crop, creationDate, endDate, threshold, weatherCondition, weatherConMax, weatherConMin, isActive, requestHistory); } function getBaseData() public view returns (address, address, uint256, Job[] memory, bool) { return(creator, icFactory, creationDate, jobIds, isActive); } // dev functions function setEndDateNow() external onlyIcFactory { endDate = block.timestamp; } }
checks that the contract period has not yet been exceeded.
function isPeriod() internal view returns(bool) { return (endDate >= block.timestamp); }
1,087,785
[ 1, 12366, 716, 326, 6835, 3879, 711, 486, 4671, 2118, 12428, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 5027, 1435, 2713, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 327, 261, 409, 1626, 1545, 1203, 18, 5508, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import { IStandarERC721 } from "../IStandarERC721.sol"; import { IStandarERC1155 } from "../IStandarERC1155.sol"; import { CrossDomainEnabled } from "../gateway/CrossDomainEnabled.sol"; import { Lib_PredeployAddresses } from "../gateway/Lib_PredeployAddresses.sol"; import { iOVM_GasPriceOracle } from "../gateway/iOVM_GasPriceOracle.sol"; import { ICrollDomain } from "../ICrollDomain.sol"; import { CommonEvent } from "../CommonEvent.sol"; import { INFTDeposit } from "../INFTDeposit.sol"; contract L2NFTBridge is AccessControl, CrossDomainEnabled, CommonEvent { // rollback bytes32 public constant ROLLBACK_ROLE = keccak256("ROLLBACK_ROLE"); // L1 bridge address public destNFTBridge; // L2 nft deposit address public localNFTDeposit; // get current chainid function getChainID() internal view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } // nft supported enum nftenum { ERC721, ERC1155 } // L2 nft => L1 nft mapping(address => address) public clone; // L2 nft => is the original mapping(address => bool) public isOrigin; // L2 nft => L2 nft id => is deposited mapping(address => mapping( uint256 => bool )) public isDeposit; // L2 nft => L2 nft id => deposit user mapping(address => mapping( uint256 => address )) public depositUser; modifier onlyEOA() { require(!Address.isContract(msg.sender), "Account not EOA"); _; } constructor(address _owner, address _rollback, address _localMessenger) CrossDomainEnabled(_localMessenger) { _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(ROLLBACK_ROLE, _rollback); } /** config * * @param _localNFTDeposit L2 deposit * @param _destNFTBridge L1 bridge */ function set(address _localNFTDeposit, address _destNFTBridge) public onlyRole(DEFAULT_ADMIN_ROLE) { require(destNFTBridge == address(0), "Already configured."); localNFTDeposit = _localNFTDeposit; destNFTBridge = _destNFTBridge; emit EVENT_SET(localNFTDeposit, destNFTBridge); } /** L1 bridge role config nft clone * * @param localNFT nft on this chain * @param destNFT nft on L1 * @param originNFTChainId origin NFT ChainId */ function configNFT(address destNFT, address localNFT, uint256 originNFTChainId) external virtual onlyFromCrossDomainAccount(destNFTBridge) { clone[localNFT] = destNFT; uint256 localChainId = getChainID(); isOrigin[localNFT] = false; if(localChainId == originNFTChainId){ isOrigin[localNFT] = true; } emit CONFIT_NFT(localNFT, destNFT, originNFTChainId); } /** deposit nft into L2 deposit * * @param localNFT nft on this chain * @param destTo owns nft on L1 * @param id nft id * @param nftStandard nft type * @param destGas L1 gas */ function depositTo(address localNFT, address destTo, uint256 id, nftenum nftStandard, uint32 destGas) external payable onlyEOA() { require(clone[localNFT] != address(0), "NFT not config."); require(isDeposit[localNFT][id] == false, "Don't redeposit."); uint256 minL1Gas = iOVM_GasPriceOracle(Lib_PredeployAddresses.OVM_GASPRICE_ORACLE).minErc20BridgeCost(); require (msg.value >= minL1Gas, string(abi.encodePacked("insufficient depositTo fee supplied. need at least ", uint2str(minL1Gas)))); uint256 amount = 0; if(nftenum.ERC721 == nftStandard) { IERC721(localNFT).safeTransferFrom(msg.sender, localNFTDeposit, id); } if(nftenum.ERC1155 == nftStandard) { amount = IERC1155(localNFT).balanceOf(msg.sender, id); require(amount == 1, "Not an NFT token."); IERC1155(localNFT).safeTransferFrom(msg.sender, localNFTDeposit, id, amount, ""); } _depositStatus(localNFT, id, msg.sender, true); address destNFT = clone[localNFT]; _messenger(destNFT, msg.sender, destTo, id, amount, uint8(nftStandard), destGas); emit DEPOSIT_TO(destNFT, msg.sender, destTo, id, amount, uint8(nftStandard)); } function _depositStatus(address _nft, uint256 _id, address _user, bool _isDeposit) internal { isDeposit[_nft][_id] = _isDeposit; depositUser[_nft][_id] = _user; } /** deposit messenger * * @param destNFT nft on L1 * @param from msg.sender * @param destTo owns nft on L1 * @param id nft id * @param amount amount * @param nftStandard nft type * @param destGas L1 gas */ function _messenger(address destNFT, address from, address destTo, uint256 id, uint256 amount, uint8 nftStandard, uint32 destGas) internal { bytes memory message = abi.encodeWithSelector( ICrollDomain.finalizeDeposit.selector, destNFT, from, destTo, id, amount, nftStandard ); sendCrossDomainMessage( destNFTBridge, destGas, message, msg.value ); } /** clone nft * * @param _localNFT nft * @param _destFrom owns nft on l2 * @param _localTo give to * @param id nft id * @param _amount nft amount * @param nftStandard nft type */ function finalizeDeposit(address _localNFT, address _destFrom, address _localTo, uint256 id, uint256 _amount, nftenum nftStandard) external virtual onlyFromCrossDomainAccount(destNFTBridge) { if(nftenum.ERC721 == nftStandard) { if(isDeposit[_localNFT][id]){ INFTDeposit(localNFTDeposit).withdrawERC721(_localNFT, _localTo, id); }else{ if(isOrigin[_localNFT]){ // What happened emit DEPOSIT_FAILED(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard)); }else{ IStandarERC721(_localNFT).mint(_localTo, id); } } } if(nftenum.ERC1155 == nftStandard) { if(isDeposit[_localNFT][id]){ INFTDeposit(localNFTDeposit).withdrawERC1155(_localNFT, _localTo, id, _amount); }else{ if(isOrigin[_localNFT]){ // What happened emit DEPOSIT_FAILED(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard)); }else{ IStandarERC1155(_localNFT).mint(_localTo, id, _amount, ""); } } } _depositStatus(_localNFT, id, address(0), false); emit FINALIZE_DEPOSIT(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard)); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } /** hack rollback * * @param nftStandard nft type * @param _localNFT nft * @param ids tokenid */ function rollback(nftenum nftStandard, address _localNFT, uint256[] memory ids) public onlyRole(ROLLBACK_ROLE) { for( uint256 index; index < ids.length; index++ ){ uint256 id = ids[index]; address _depositUser = depositUser[_localNFT][id]; require(isDeposit[_localNFT][id], "Not Deposited"); require(_depositUser != address(0), "user can not be zero address."); uint256 amount = 0; if(nftenum.ERC721 == nftStandard) { INFTDeposit(localNFTDeposit).withdrawERC721(_localNFT, _depositUser, id); }else{ amount = 1; INFTDeposit(localNFTDeposit).withdrawERC1155(_localNFT, _depositUser, id, amount); } _depositStatus(_localNFT, id, address(0), false); emit ROLLBACK(_localNFT, localNFTDeposit, _depositUser, id, amount, uint8(nftStandard)); } } }
* config @param _localNFTDeposit L2 deposit @param _destNFTBridge L1 bridge/
function set(address _localNFTDeposit, address _destNFTBridge) public onlyRole(DEFAULT_ADMIN_ROLE) { require(destNFTBridge == address(0), "Already configured."); localNFTDeposit = _localNFTDeposit; destNFTBridge = _destNFTBridge; emit EVENT_SET(localNFTDeposit, destNFTBridge); }
7,219,613
[ 1, 1425, 225, 389, 3729, 50, 4464, 758, 1724, 511, 22, 443, 1724, 225, 389, 10488, 50, 4464, 13691, 511, 21, 10105, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 12, 2867, 389, 3729, 50, 4464, 758, 1724, 16, 1758, 389, 10488, 50, 4464, 13691, 13, 1071, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 288, 203, 540, 203, 3639, 2583, 12, 10488, 50, 4464, 13691, 422, 1758, 12, 20, 3631, 315, 9430, 4351, 1199, 1769, 203, 203, 3639, 1191, 50, 4464, 758, 1724, 273, 389, 3729, 50, 4464, 758, 1724, 31, 203, 3639, 1570, 50, 4464, 13691, 273, 389, 10488, 50, 4464, 13691, 31, 203, 203, 3639, 3626, 9964, 67, 4043, 12, 3729, 50, 4464, 758, 1724, 16, 1570, 50, 4464, 13691, 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 ]
/** * Token recurring billing smart contract, which enable recurring billing feature for DREAM token. * Developed by DreamTeam.GG contributors. Visit dreamteam.gg and github.com/dreamteam-gg/smart-contracts for more info. * Copyright © 2019 DREAMTEAM. * Licensed under the Apache License, Version 2.0 (the "License"). */ pragma solidity 0.5.2; interface ERC20CompatibleToken { function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer (address to, uint tokens) external returns (bool success); function transferFrom (address from, address to, uint tokens) external returns (bool success); } /** * Math operations with safety checks that throw on overflows. */ library SafeMath { function mul (uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b); return c; } function div (uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub (uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add (uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); return c; } } /** * Smart contract for recurring billing in ERC20-compatible tokens. This smart contract defines workflow between * a merchant and a customer. Workflow: * 1. Merchant registers theirselves in this smart contract using `registerNewMerchant`. * 1.1. Merchant specifies `beneficiary` address, which receives tokens. * 1.2. Merchant specifies `merchant` address, which is able to change `merchant` and `beneficiary` addresses. * 1.3. Merchant specified an address that is authorized to call `charge` related to this merchant. * 1.3.1. Later, merchant can (de)authorize another addresses to call `charge` using `changeMerchantChargingAccount`. * 1.4. As a result, merchant gets `merchantId`, which is used to initialize recurring billing by customers. * 1.5. Merchant account can change their `beneficiary`, `merchant` and authorized charging addresses by calling: * 1.4.1. Function `changeMerchantAccount`, which changes account that can control this merchant (`merchantId`). * 1.4.2. Function `changeMerchantBeneficiaryAddress`, which changes merchant's `beneficiary`. * 1.4.3. Function `changeMerchantChargingAccount`, which (de)authorizes addresses to call `charge` on behalf of this merchant. * 2. According to an off-chain agreement with merchant, customer calls `allowRecurringBilling` and: * 2.1. Specifies `billingId`, which is given off-chain by merchant (merchant will listen blockchain Event on this ID). * 2.2. Specifies `merchantId`, the merchant which will receive tokens. * 2.3. Specifies `period` in seconds, during which only one charge can occur. * 2.4. Specifies `value`, amount in tokens which can be charged each `period`. * 2.4.1. If the customer doesn't have at least `value` tokens, `allowRecurringBilling` errors. * 2.4.2. If the customer haven't approved at least `value` tokens for a smart contract, `allowRecurringBilling` errors. * 2.5. `billingId` is then used by merchant to charge customer each `period`. * 3. Merchant use authorized accounts (1.3) to call the `charge` function each `period` to charge agreed amount from a customer. * 3.1. It is impossible to call `charge` if the date of the last charge is less than `period`. * 3.2. Calling `charge` cancels billing when called after 2 `period`s from the last charge. * 3.3. Thus, to successfully charge an account, `charge` must be strictly called within 1 and 2 `period`s after the last charge. * 3.4. Calling `charge` errors if any of the following occur: * 3.4.1. Customer canceled recurring billing with `cancelRecurringBilling`. * 3.4.2. Customer's balance is lower than the chargeable amount. * 3.4.3. Customer's allowance to the smart contract is less than the chargable amount. * 3.4.4. Specified `billingId` does not exists. * 3.4.5. There's no `period` passed since the last charge. * 3.5. Next charge date increments strictly by `period` each charge, thus, there's no need to exec `charge` strictly on time. * 4. Customer can cancel further billing by calling `cancelRecurringBilling` and passing `billingId`. * 5. TokenRecurringBilling smart contract implements `receiveApproval` function for allowing/cancelling billing within one call from * the token smart contract. Parameter `data` is encoded as tightly-packed (uint256 metadata, uint256 billingId). * 5.1. `metadata` is encoded using `encodeBillingMetadata`. * 5.2. As for `receiveApproval`, `lastChargeAt` in `metadata` is used as an action identifier. * 5.2.1. `lastChargeAt=0` specifies that customer wants to allow new recurring billing. * 5.2.2. `lastChargeAt=1` specifies that customer wants to cancel existing recurring billing. * 5.3. Make sure that passed `bytes` parameter is exactly 64 bytes in length. */ contract TokenRecurringBilling { using SafeMath for uint256; event BillingAllowed(uint256 indexed billingId, address customer, uint256 merchantId, uint256 timestamp, uint256 period, uint256 value); event BillingCharged(uint256 indexed billingId, uint256 timestamp, uint256 nextChargeTimestamp); event BillingCanceled(uint256 indexed billingId); event MerchantRegistered(uint256 indexed merchantId, address merchantAccount, address beneficiaryAddress); event MerchantAccountChanged(uint256 indexed merchantId, address merchantAccount); event MerchantBeneficiaryAddressChanged(uint256 indexed merchantId, address beneficiaryAddress); event MerchantChargingAccountAllowed(uint256 indexed merchantId, address chargingAccount, bool allowed); struct BillingRecord { address customer; // Billing address (those who pay). uint256 metadata; // Metadata packs 5 values to save on storage. Metadata spec (from first to last byte): // + uint32 period; // Billing period in seconds; configurable period of up to 136 years. // + uint32 merchantId; // Merchant ID; up to ~4.2 Milliard IDs. // + uint48 lastChargeAt; // When the last charge occurred; up to year 999999+. // + uint144 value; // Billing value charrged each period; up to ~22 septillion tokens with 18 decimals } struct Merchant { address merchant; // Merchant admin address that can change all merchant struct properties. address beneficiary; // Address receiving tokens. } enum receiveApprovalAction { // In receiveApproval, `lastChargeAt` in passed `metadata` specifies an action to execute. allowRecurringBilling, // == 0 cancelRecurringBilling // == 1 } uint256 public lastMerchantId; // This variable increments on each new merchant registered, generating unique ids for merchant. ERC20CompatibleToken public token; // Token address. mapping(uint256 => BillingRecord) public billingRegistry; // List of all billings registered by ID. mapping(uint256 => Merchant) public merchantRegistry; // List of all merchants registered by ID. mapping(uint256 => mapping(address => bool)) public merchantChargingAccountAllowed; // Accounts that are allowed to charge customers. // Checks whether {merchant} owns {merchantId} modifier isMerchant (uint256 merchantId) { require(merchantRegistry[merchantId].merchant == msg.sender, "Sender is not a merchant"); _; } // Checks whether {customer} owns {billingId} modifier isCustomer (uint256 billingId) { require(billingRegistry[billingId].customer == msg.sender, "Sender is not a customer"); _; } // Guarantees that the transaction is sent by token smart contract only. modifier tokenOnly () { require(msg.sender == address(token), "Sender is not a token"); _; } /// ======================================================== Constructor ========================================================= \\\ // Creates a recurring billing smart contract for particular token. constructor (address tokenAddress) public { token = ERC20CompatibleToken(tokenAddress); } /// ====================================================== Public Functions ====================================================== \\\ // Enables merchant with {merchantId} to charge transaction signer's account according to specified {value} and {period}. function allowRecurringBilling (uint256 billingId, uint256 merchantId, uint256 value, uint256 period) public { allowRecurringBillingInternal(msg.sender, merchantId, billingId, value, period); } // Enables anyone to become a merchant, charging tokens for their services. function registerNewMerchant (address beneficiary, address chargingAccount) public returns (uint256 merchantId) { merchantId = ++lastMerchantId; Merchant storage record = merchantRegistry[merchantId]; record.merchant = msg.sender; record.beneficiary = beneficiary; emit MerchantRegistered(merchantId, msg.sender, beneficiary); changeMerchantChargingAccount(merchantId, chargingAccount, true); } /// =========================================== Public Functions with Restricted Access =========================================== \\\ // Calcels recurring billing with id {billingId} if it is owned by a transaction signer. function cancelRecurringBilling (uint256 billingId) public isCustomer(billingId) { cancelRecurringBillingInternal(billingId); } // Charges customer's account according to defined {billingId} billing rules. Only merchant's authorized accounts can charge the customer. function charge (uint256 billingId) public { BillingRecord storage billingRecord = billingRegistry[billingId]; (uint256 value, uint256 lastChargeAt, uint256 merchantId, uint256 period) = decodeBillingMetadata(billingRecord.metadata); require(merchantChargingAccountAllowed[merchantId][msg.sender], "Sender is not allowed to charge"); require(merchantId != 0, "Billing does not exist"); require(lastChargeAt.add(period) <= now, "Charged too early"); // If 2 periods have already passed since the last charge (or beginning), no further charges are possible // and recurring billing is canceled in case of a charge. if (now > lastChargeAt.add(period.mul(2))) { cancelRecurringBillingInternal(billingId); return; } require( token.transferFrom(billingRecord.customer, merchantRegistry[merchantId].beneficiary, value), "Unable to charge customer" ); billingRecord.metadata = encodeBillingMetadata(value, lastChargeAt.add(period), merchantId, period); emit BillingCharged(billingId, now, lastChargeAt.add(period.mul(2))); } /** * Invoked by a token smart contract on approveAndCall. Allows or cancels recurring billing. * @param sender - Address that approved some tokens for this smart contract. * @param data - Tightly-packed (uint256,uint256) values of (metadata, billingId). Metadata's `lastChargeAt` * specifies an action to perform (see `receiveApprovalAction` enum). */ function receiveApproval (address sender, uint, address, bytes calldata data) external tokenOnly { // The token contract MUST guarantee that "sender" is actually the token owner, and metadata is signed by a token owner. require(data.length == 64, "Invalid data length"); // `action` is used instead of `lastCahrgeAt` to save some space. (uint256 value, uint256 action, uint256 merchantId, uint256 period) = decodeBillingMetadata(bytesToUint256(data, 0)); uint256 billingId = bytesToUint256(data, 32); if (action == uint256(receiveApprovalAction.allowRecurringBilling)) { allowRecurringBillingInternal(sender, merchantId, billingId, value, period); } else if (action == uint256(receiveApprovalAction.cancelRecurringBilling)) { require(billingRegistry[billingId].customer == sender, "Unable to cancel recurring billing of another customer"); cancelRecurringBillingInternal(billingId); } else { revert("Unknown action provided"); } } // Changes merchant account with id {merchantId} to {newMerchantAccount}. function changeMerchantAccount (uint256 merchantId, address newMerchantAccount) public isMerchant(merchantId) { merchantRegistry[merchantId].merchant = newMerchantAccount; emit MerchantAccountChanged(merchantId, newMerchantAccount); } // Changes merchant's beneficiary address (address that receives charged tokens) to {newBeneficiaryAddress}. function changeMerchantBeneficiaryAddress (uint256 merchantId, address newBeneficiaryAddress) public isMerchant(merchantId) { merchantRegistry[merchantId].beneficiary = newBeneficiaryAddress; emit MerchantBeneficiaryAddressChanged(merchantId, newBeneficiaryAddress); } // Allows or disallows particular {account} to charge customers related to this merchant. function changeMerchantChargingAccount (uint256 merchantId, address account, bool allowed) public isMerchant(merchantId) { merchantChargingAccountAllowed[merchantId][account] = allowed; emit MerchantChargingAccountAllowed(merchantId, account, allowed); } /// ================================================== Public Utility Functions ================================================== \\\ // Used to encode 5 values into one uint256 value. This is primarily made for cheaper storage. function encodeBillingMetadata ( uint256 value, uint256 lastChargeAt, uint256 merchantId, uint256 period ) public pure returns (uint256 result) { require( value < 2 ** 144 && lastChargeAt < 2 ** 48 && merchantId < 2 ** 32 && period < 2 ** 32, "Invalid input sizes to encode" ); result = value; result |= lastChargeAt << (144); result |= merchantId << (144 + 48); result |= period << (144 + 48 + 32); return result; } // Used to decode 5 values from one uint256 value encoded by `encodeBillingMetadata` function. function decodeBillingMetadata (uint256 encodedData) public pure returns ( uint256 value, uint256 lastChargeAt, uint256 merchantId, uint256 period ) { value = uint144(encodedData); lastChargeAt = uint48(encodedData >> (144)); merchantId = uint32(encodedData >> (144 + 48)); period = uint32(encodedData >> (144 + 48 + 32)); } /// ================================================ Internal (Private) Functions ================================================ \\\ // Allows recurring billing. Noone but this contract can call this function. function allowRecurringBillingInternal ( address customer, uint256 merchantId, uint256 billingId, uint256 value, uint256 period ) internal { require(merchantId <= lastMerchantId && merchantId != 0, "Invalid merchant specified"); require(period < now, "Invalid period specified"); require(token.balanceOf(customer) >= value, "Not enough tokens for the first charge"); require(token.allowance(customer, address(this)) >= value, "Tokens are not approved for this smart contract"); require(billingRegistry[billingId].customer == address(0x0), "Recurring billing with this ID is already registered"); BillingRecord storage newRecurringBilling = billingRegistry[billingId]; newRecurringBilling.metadata = encodeBillingMetadata(value, now.sub(period), merchantId, period); newRecurringBilling.customer = customer; emit BillingAllowed(billingId, customer, merchantId, now, period, value); } // Cancels recurring billing. Noone but this contract can call this function. function cancelRecurringBillingInternal (uint256 billingId) internal { delete billingRegistry[billingId]; emit BillingCanceled(billingId); } // Utility function to convert bytes type to uint256. Noone but this contract can call this function. function bytesToUint256(bytes memory input, uint offset) internal pure returns (uint256 output) { assembly { output := mload(add(add(input, 32), offset)) } } }
Changes merchant account with id {merchantId} to {newMerchantAccount}.
function changeMerchantAccount (uint256 merchantId, address newMerchantAccount) public isMerchant(merchantId) { merchantRegistry[merchantId].merchant = newMerchantAccount; emit MerchantAccountChanged(merchantId, newMerchantAccount); }
11,861,003
[ 1, 7173, 20411, 2236, 598, 612, 288, 25705, 548, 97, 358, 288, 2704, 27218, 3032, 5496, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2549, 27218, 3032, 261, 11890, 5034, 20411, 548, 16, 1758, 394, 27218, 3032, 13, 1071, 353, 27218, 12, 25705, 548, 13, 288, 203, 3639, 20411, 4243, 63, 25705, 548, 8009, 25705, 273, 394, 27218, 3032, 31, 203, 3639, 3626, 14940, 11106, 3032, 5033, 12, 25705, 548, 16, 394, 27218, 3032, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.17; /** * @title Interface for contract governance/Staking/Staking.sol * @dev Interfaces are used to cast a contract address into a callable instance. */ interface IStaking { function stakesBySchedule( uint256 amount, uint256 cliff, uint256 duration, uint256 intervalLength, address stakeFor, address delegatee ) external; function stake( uint96 amount, uint256 until, address stakeFor, address delegatee ) external; function getPriorVotes( address account, uint256 blockNumber, uint256 date ) external view returns (uint96); function getPriorTotalVotingPower(uint32 blockNumber, uint256 time) external view returns (uint96); function getPriorWeightedStake( address account, uint256 blockNumber, uint256 date ) external view returns (uint96); function getPriorVestingWeightedStake(uint256 blockNumber, uint256 date) external view returns (uint96); function timestampToLockDate(uint256 timestamp) external view returns (uint256 lockDate); function isVestingContract(address stakerAddress) external view returns (bool); }
* @title Interface for contract governance/Staking/Staking.sol @dev Interfaces are used to cast a contract address into a callable instance./
interface IStaking { function stakesBySchedule( uint256 amount, uint256 cliff, uint256 duration, uint256 intervalLength, address stakeFor, address delegatee ) external; function stake( uint96 amount, uint256 until, address stakeFor, address delegatee ) external; function getPriorVotes( address account, uint256 blockNumber, uint256 date ) external view returns (uint96); function getPriorTotalVotingPower(uint32 blockNumber, uint256 time) external view returns (uint96); function getPriorWeightedStake( address account, uint256 blockNumber, uint256 date ) external view returns (uint96); function getPriorVestingWeightedStake(uint256 blockNumber, uint256 date) external view returns (uint96); function timestampToLockDate(uint256 timestamp) external view returns (uint256 lockDate); function isVestingContract(address stakerAddress) external view returns (bool); }
12,868,937
[ 1, 1358, 364, 6835, 314, 1643, 82, 1359, 19, 510, 6159, 19, 510, 6159, 18, 18281, 225, 27152, 854, 1399, 358, 4812, 279, 6835, 1758, 1368, 279, 4140, 791, 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, 5831, 467, 510, 6159, 288, 203, 565, 445, 384, 3223, 858, 6061, 12, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 927, 3048, 16, 203, 3639, 2254, 5034, 3734, 16, 203, 3639, 2254, 5034, 3673, 1782, 16, 203, 3639, 1758, 384, 911, 1290, 16, 203, 3639, 1758, 7152, 73, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 384, 911, 12, 203, 3639, 2254, 10525, 3844, 16, 203, 3639, 2254, 5034, 3180, 16, 203, 3639, 1758, 384, 911, 1290, 16, 203, 3639, 1758, 7152, 73, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 1689, 2432, 29637, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 1203, 1854, 16, 203, 3639, 2254, 5034, 1509, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 10525, 1769, 203, 203, 565, 445, 1689, 2432, 5269, 58, 17128, 13788, 12, 11890, 1578, 1203, 1854, 16, 2254, 5034, 813, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 10525, 1769, 203, 203, 565, 445, 1689, 2432, 6544, 329, 510, 911, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 1203, 1854, 16, 203, 3639, 2254, 5034, 1509, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 10525, 1769, 203, 203, 565, 445, 1689, 2432, 58, 10100, 6544, 329, 510, 911, 12, 11890, 5034, 1203, 1854, 16, 2254, 5034, 1509, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 10525, 1769, 203, 203, 565, 445, 2858, 774, 2531, 1626, 12, 11890, 5034, 2858, 13, 3903, 1476, 1135, 261, 11890, 5034, 2176, 1626, 2 ]
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2021 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"; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; import "../migrations/LibMigrate.sol"; import "../fixins/FixinCommon.sol"; import "./interfaces/IFeature.sol"; import "./interfaces/IPancakeSwapFeature.sol"; /// @dev VIP pancake fill functions. contract PancakeSwapFeature is IFeature, IPancakeSwapFeature, FixinCommon { /// @dev Name of this feature. string public constant override FEATURE_NAME = "PancakeSwapFeature"; /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 1); /// @dev WBNB contract. IEtherTokenV06 private immutable WBNB; // 0xFF + address of the PancakeSwap factory contract. uint256 constant private FF_PANCAKESWAP_FACTORY = 0xffbcfccbde45ce874adcb698cc183debcf179528120000000000000000000000; // 0xFF + address of the BakerySwap factory contract. uint256 constant private FF_BAKERYSWAP_FACTORY = 0xff01bf7c66c6bd861915cdaae475042d3c4bae16a70000000000000000000000; // 0xFF + address of the SushiSwap factory contract. uint256 constant private FF_SUSHISWAP_FACTORY = 0xffc35DADB65012eC5796536bD9864eD8773aBc74C40000000000000000000000; // Init code hash of the PancakeSwap pair contract. uint256 constant private PANCAKESWAP_PAIR_INIT_CODE_HASH = 0xd0d4c4cd0848c93cb4fd1f498d7013ee6bfb25783ea21593d5834f5d250ece66; // Init code hash of the BakerySwap pair contract. uint256 constant private BAKERYSWAP_PAIR_INIT_CODE_HASH = 0xe2e87433120e32c4738a7d8f3271f3d872cbe16241d67537139158d90bac61d3; // Init code hash of the SushiSwap pair contract. uint256 constant private SUSHISWAP_PAIR_INIT_CODE_HASH = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // Mask of the lower 20 bytes of a bytes32. uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; // BNB pseudo-token address. uint256 constant private ETH_TOKEN_ADDRESS_32 = 0x000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; // Maximum token quantity that can be swapped against the PancakeSwapPair contract. uint256 constant private MAX_SWAP_AMOUNT = 2**112; // bytes4(keccak256("executeCall(address,bytes)")) uint256 constant private ALLOWANCE_TARGET_EXECUTE_CALL_SELECTOR_32 = 0xbca8c7b500000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("getReserves()")) uint256 constant private PANCAKESWAP_PAIR_RESERVES_CALL_SELECTOR_32 = 0x0902f1ac00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("swap(uint256,uint256,address,bytes)")) uint256 constant private PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x022c0d9f00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("swap(uint256,uint256,address)")) uint256 constant private BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x6d9a640a00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("transferFrom(address,address,uint256)")) uint256 constant private TRANSFER_FROM_CALL_SELECTOR_32 = 0x23b872dd00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("allowance(address,address)")) uint256 constant private ALLOWANCE_CALL_SELECTOR_32 = 0xdd62ed3e00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("withdraw(uint256)")) uint256 constant private WETH_WITHDRAW_CALL_SELECTOR_32 = 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("deposit()")) uint256 constant private WETH_DEPOSIT_CALL_SELECTOR_32 = 0xd0e30db000000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("transfer(address,uint256)")) uint256 constant private ERC20_TRANSFER_CALL_SELECTOR_32 = 0xa9059cbb00000000000000000000000000000000000000000000000000000000; /// @dev Construct this contract. /// @param wbnb The WBNB contract. constructor(IEtherTokenV06 wbnb) public { WBNB = wbnb; } /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellToPancakeSwap.selector); return LibMigrate.MIGRATE_SUCCESS; } /// @dev Efficiently sell directly to pancake/BakerySwap/SushiSwap. /// @param tokens Sell path. /// @param sellAmount of `tokens[0]` Amount to sell. /// @param minBuyAmount Minimum amount of `tokens[-1]` to buy. /// @param fork The protocol fork to use. /// @return buyAmount Amount of `tokens[-1]` bought. function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { // Load immutables onto the stack. IEtherTokenV06 wbnb = WBNB; // Store some vars in memory to get around stack limits. assembly { // calldataload(mload(0xA00)) == first element of `tokens` array mstore(0xA00, add(calldataload(0x04), 0x24)) // mload(0xA20) == fork mstore(0xA20, fork) // mload(0xA40) == WBNB mstore(0xA40, wbnb) } } assembly { // numPairs == tokens.length - 1 let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) // We use the previous buy amount as the sell amount for the next // pair in a path. So for the first swap we want to set it to `sellAmount`. buyAmount := sellAmount let buyToken let nextPair := 0 for {let i := 0} lt(i, numPairs) {i := add(i, 1)} { // sellToken = tokens[i] let sellToken := loadTokenAddress(i) // buyToken = tokens[i+1] buyToken := loadTokenAddress(add(i, 1)) // The canonical ordering of this token pair. let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) // Compute the pair address if it hasn't already been computed // from the last iteration. let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { // This is the first token in the path. switch eq(sellToken, ETH_TOKEN_ADDRESS_32) case 0 { // Not selling BNB. Selling an ERC20 instead. // Make sure BNB was not attached to the call. if gt(callvalue(), 0) { revert(0, 0) } // For the first pair we need to transfer sellTokens into the // pair contract. moveTakerTokensTo(sellToken, pair, sellAmount) } default { // If selling BNB, we need to wrap it to WBNB and transfer to the // pair contract. if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } sellToken := mload(0xA40)// Re-assign to WBNB // Call `WBNB.deposit{value: sellAmount}()` mstore(0xB00, WETH_DEPOSIT_CALL_SELECTOR_32) if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } // Call `WBNB.transfer(pair, sellAmount)` mstore(0xB00, ERC20_TRANSFER_CALL_SELECTOR_32) mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } // No need to check results, if deposit/transfers failed the PancakeSwapPair will // reject our trade (or it may succeed if somehow the reserve was out of sync) // this is fine for the taker. } // Call pair.getReserves(), store the results at `0xC00` mstore(0xB00, PANCAKESWAP_PAIR_RESERVES_CALL_SELECTOR_32) if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } // Revert if the pair contract does not return at least two words. if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } // Sell amount for this hop is the previous buy amount. let pairSellAmount := buyAmount // Compute the buy amount based on the pair reserves. { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { // Transpose if pair order is different. sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } // Ensure that the sellAmount is < 2¹¹². if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } // Pairs are in the range (0, 2¹¹²) so this shouldn't overflow. // buyAmount = (pairSellAmount * 997 * buyReserve) / // (pairSellAmount * 997 + sellReserve * 1000); let sellAmountWithFee := mul(pairSellAmount, 997) buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver // Is this the last pair contract? switch eq(add(i, 1), numPairs) case 0 { // Not the last pair contract, so forward bought tokens to // the next pair contract. nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { // The last pair contract. // Forward directly to taker UNLESS they want BNB back. switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } // Call pair.swap() switch mload(0xA20) // fork case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } } // End for-loop. // If buying BNB, unwrap the WBNB first if eq(buyToken, ETH_TOKEN_ADDRESS_32) { // Call `WBNB.withdraw(buyAmount)` mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } // Transfer BNB to the caller. if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } // Functions /////////////////////////////////////////////////////// // Load a token address from the `tokens` calldata argument. function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } // Convert BNB pseudo-token addresses to WBNB. function normalizeToken(token) -> normalized { normalized := token // Translate BNB pseudo-tokens to WBNB. if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } // Compute the address of the PancakeSwapPair contract given two // tokens. function computePairAddress(tokenA, tokenB) -> pair { // Convert BNB pseudo-token addresses to WBNB. tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) // There is one contract for every combination of tokens, // which is deployed using CREATE2. // The derivation of this address is given by: // address(keccak256(abi.encodePacked( // bytes(0xFF), // address(PANCAKESWAP_FACTORY_ADDRESS), // keccak256(abi.encodePacked( // tokenA < tokenB ? tokenA : tokenB, // tokenA < tokenB ? tokenB : tokenA, // )), // bytes32(PANCAKESWAP_PAIR_INIT_CODE_HASH), // ))); // Compute the salt (the hash of the sorted tokens). // Tokens are written in reverse memory order to packed encode // them as two 20-byte values in a 40-byte chunk of memory // starting at 0xB0C. switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) // Compute the pair address by hashing all the components together. switch mload(0xA20) // fork case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } // Revert with the return data from the most recent call. function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // Move `amount` tokens from the taker/caller to `to`. function moveTakerTokensTo(token, to, amount) { // Perform a `transferFrom()` mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, // Copy only the first 32 bytes of return data. We // only care about reading a boolean in the success // case. We will use returndatacopy() in the failure case. 0x20 ) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should // return a boolean, but some return nothing or // extra data. We accept 0-length return data as // success, or at least 32 bytes that starts with // a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(0xC00), 1) // starts with uint256(1) ) ) ) if iszero(success) { // Revert with the data returned from the transferFrom call. returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } // Revert if we bought too little. require(buyAmount >= minBuyAmount, "PancakeSwapFeature/UnderBought"); } }
0xFF + address of the PancakeSwap factory contract. 0xFF + address of the BakerySwap factory contract. 0xFF + address of the SushiSwap factory contract. Init code hash of the PancakeSwap pair contract. Init code hash of the BakerySwap pair contract. Init code hash of the SushiSwap pair contract. Mask of the lower 20 bytes of a bytes32. BNB pseudo-token address. Maximum token quantity that can be swapped against the PancakeSwapPair contract. bytes4(keccak256("executeCall(address,bytes)")) bytes4(keccak256("getReserves()")) bytes4(keccak256("swap(uint256,uint256,address,bytes)")) bytes4(keccak256("swap(uint256,uint256,address)")) bytes4(keccak256("transferFrom(address,address,uint256)")) bytes4(keccak256("allowance(address,address)")) bytes4(keccak256("withdraw(uint256)")) bytes4(keccak256("deposit()")) bytes4(keccak256("transfer(address,uint256)"))
{ string public constant override FEATURE_NAME = "PancakeSwapFeature"; uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 1); IEtherTokenV06 private immutable WBNB; uint256 constant private FF_PANCAKESWAP_FACTORY = 0xffbcfccbde45ce874adcb698cc183debcf179528120000000000000000000000; uint256 constant private FF_BAKERYSWAP_FACTORY = 0xff01bf7c66c6bd861915cdaae475042d3c4bae16a70000000000000000000000; uint256 constant private FF_SUSHISWAP_FACTORY = 0xffc35DADB65012eC5796536bD9864eD8773aBc74C40000000000000000000000; uint256 constant private PANCAKESWAP_PAIR_INIT_CODE_HASH = 0xd0d4c4cd0848c93cb4fd1f498d7013ee6bfb25783ea21593d5834f5d250ece66; uint256 constant private BAKERYSWAP_PAIR_INIT_CODE_HASH = 0xe2e87433120e32c4738a7d8f3271f3d872cbe16241d67537139158d90bac61d3; uint256 constant private SUSHISWAP_PAIR_INIT_CODE_HASH = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; uint256 constant private ETH_TOKEN_ADDRESS_32 = 0x000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; uint256 constant private MAX_SWAP_AMOUNT = 2**112; uint256 constant private ALLOWANCE_TARGET_EXECUTE_CALL_SELECTOR_32 = 0xbca8c7b500000000000000000000000000000000000000000000000000000000; uint256 constant private PANCAKESWAP_PAIR_RESERVES_CALL_SELECTOR_32 = 0x0902f1ac00000000000000000000000000000000000000000000000000000000; uint256 constant private PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x022c0d9f00000000000000000000000000000000000000000000000000000000; uint256 constant private BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x6d9a640a00000000000000000000000000000000000000000000000000000000; uint256 constant private TRANSFER_FROM_CALL_SELECTOR_32 = 0x23b872dd00000000000000000000000000000000000000000000000000000000; uint256 constant private ALLOWANCE_CALL_SELECTOR_32 = 0xdd62ed3e00000000000000000000000000000000000000000000000000000000; uint256 constant private WETH_WITHDRAW_CALL_SELECTOR_32 = 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000; uint256 constant private WETH_DEPOSIT_CALL_SELECTOR_32 = 0xd0e30db000000000000000000000000000000000000000000000000000000000; uint256 constant private ERC20_TRANSFER_CALL_SELECTOR_32 = 0xa9059cbb00000000000000000000000000000000000000000000000000000000; contract PancakeSwapFeature is constructor(IEtherTokenV06 wbnb) public { WBNB = wbnb; } function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellToPancakeSwap.selector); return LibMigrate.MIGRATE_SUCCESS; } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } for {let i := 0} lt(i, numPairs) {i := add(i, 1)} { function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } moveTakerTokensTo(sellToken, pair, sellAmount) function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } mstore(0xB00, WETH_DEPOSIT_CALL_SELECTOR_32) function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } mstore(0xB00, ERC20_TRANSFER_CALL_SELECTOR_32) function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } } mstore(0xB00, PANCAKESWAP_PAIR_RESERVES_CALL_SELECTOR_32) function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } let pairSellAmount := buyAmount function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } let sellAmountWithFee := mul(pairSellAmount, 997) switch eq(add(i, 1), numPairs) function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } function sellToPancakeSwap( IERC20TokenV06[] calldata tokens, uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { IEtherTokenV06 wbnb = WBNB; assembly { mstore(0xA00, add(calldataload(0x04), 0x24)) mstore(0xA20, fork) mstore(0xA40, wbnb) } } assembly { let numPairs := sub(calldataload(add(calldataload(0x04), 0x4)), 1) buyAmount := sellAmount let buyToken let nextPair := 0 let sellToken := loadTokenAddress(i) buyToken := loadTokenAddress(add(i, 1)) let pairOrder := lt(normalizeToken(sellToken), normalizeToken(buyToken)) let pair := nextPair if iszero(pair) { pair := computePairAddress(sellToken, buyToken) nextPair := 0 } if iszero(i) { switch eq(sellToken, ETH_TOKEN_ADDRESS_32) if gt(callvalue(), 0) { revert(0, 0) } } default { if iszero(eq(callvalue(), sellAmount)) { revert(0, 0) } if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { bubbleRevert() } mstore(0xB04, pair) mstore(0xB24, sellAmount) if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { bubbleRevert() } } if iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) { bubbleRevert() } if lt(returndatasize(), 0x40) { mstore(0, pair) revert(0, 32) } { let sellReserve let buyReserve switch iszero(pairOrder) case 0 { sellReserve := mload(0xC00) buyReserve := mload(0xC20) } default { sellReserve := mload(0xC20) buyReserve := mload(0xC00) } if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) } buyAmount := div( mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000)) ) } let receiver case 0 { nextPair := computePairAddress( buyToken, loadTokenAddress(add(i, 2)) ) receiver := nextPair } default { switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { receiver := caller() } default { receiver := address() } } case 1 { mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) } default { mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) } switch pairOrder case 0 { mstore(0xB04, buyAmount) mstore(0xB24, 0) } default { mstore(0xB04, 0) mstore(0xB24, buyAmount) } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) if iszero(call(gas(), pair, 0, 0xB00, 0xA4, 0, 0)) { bubbleRevert() } if eq(buyToken, ETH_TOKEN_ADDRESS_32) { mstore(0xB00, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(0xB04, buyAmount) if iszero(call(gas(), mload(0xA40), 0, 0xB00, 0x24, 0x00, 0x0)) { bubbleRevert() } if iszero(call(gas(), caller(), buyAmount, 0xB00, 0x0, 0x00, 0x0)) { bubbleRevert() } } function loadTokenAddress(idx) -> addr { addr := and(ADDRESS_MASK, calldataload(add(mload(0xA00), mul(idx, 0x20)))) } function normalizeToken(token) -> normalized { normalized := token if eq(token, ETH_TOKEN_ADDRESS_32) { normalized := mload(0xA40) } } function computePairAddress(tokenA, tokenB) -> pair { tokenA := normalizeToken(tokenA) tokenB := normalizeToken(tokenB) switch lt(tokenA, tokenB) case 0 { mstore(0xB14, tokenA) mstore(0xB00, tokenB) } default { mstore(0xB14, tokenB) mstore(0xB00, tokenA) } let salt := keccak256(0xB0C, 0x28) case 0 { mstore(0xB00, FF_PANCAKESWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) } case 1 { mstore(0xB00, FF_BAKERYSWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) } default { mstore(0xB00, FF_SUSHISWAP_FACTORY) mstore(0xB15, salt) mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } function bubbleRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function moveTakerTokensTo(token, to, amount) { mstore(0xB00, TRANSFER_FROM_CALL_SELECTOR_32) mstore(0xB04, caller()) mstore(0xB24, to) mstore(0xB44, amount) let success := call( gas(), token, 0, 0xB00, 0x64, 0xC00, 0x20 ) let rdsize := returndatasize() success := and( or( and( ) ) ) if iszero(success) { returndatacopy(0, 0, rdsize) revert(0, rdsize) } } } require(buyAmount >= minBuyAmount, "PancakeSwapFeature/UnderBought"); }
6,452,051
[ 1, 20, 6356, 397, 1758, 434, 326, 12913, 23780, 12521, 3272, 6835, 18, 374, 6356, 397, 1758, 434, 326, 605, 581, 627, 12521, 3272, 6835, 18, 374, 6356, 397, 1758, 434, 326, 348, 1218, 77, 12521, 3272, 6835, 18, 4378, 981, 1651, 434, 326, 12913, 23780, 12521, 3082, 6835, 18, 4378, 981, 1651, 434, 326, 605, 581, 627, 12521, 3082, 6835, 18, 4378, 981, 1651, 434, 326, 348, 1218, 77, 12521, 3082, 6835, 18, 16698, 434, 326, 2612, 4200, 1731, 434, 279, 1731, 1578, 18, 605, 20626, 12454, 17, 2316, 1758, 18, 18848, 1147, 10457, 716, 848, 506, 7720, 1845, 5314, 326, 12913, 23780, 12521, 4154, 6835, 18, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 8837, 1477, 12, 2867, 16, 3890, 2225, 3719, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 588, 607, 264, 3324, 10031, 3719, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 22270, 12, 11890, 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, 95, 203, 565, 533, 1071, 5381, 3849, 25201, 67, 1985, 273, 315, 4069, 23780, 12521, 4595, 14432, 203, 565, 2254, 5034, 1071, 11732, 3849, 25201, 67, 5757, 273, 389, 3015, 1444, 12, 21, 16, 374, 16, 404, 1769, 203, 565, 10897, 1136, 1345, 58, 7677, 3238, 11732, 678, 15388, 38, 31, 203, 203, 565, 2254, 5034, 5381, 3238, 6512, 67, 30819, 3587, 47, 3991, 59, 2203, 67, 16193, 273, 374, 5297, 70, 8522, 952, 70, 323, 7950, 311, 28, 5608, 361, 7358, 8148, 28, 952, 31672, 31888, 8522, 4033, 8778, 6030, 2138, 12648, 12648, 9449, 31, 203, 565, 2254, 5034, 5381, 3238, 6512, 67, 12536, 47, 8404, 18746, 2203, 67, 16193, 273, 374, 5297, 1611, 17156, 27, 71, 6028, 71, 26, 16410, 5292, 3657, 3600, 71, 2414, 8906, 24, 5877, 3028, 22, 72, 23, 71, 24, 70, 8906, 2313, 69, 27, 12648, 12648, 9449, 31, 203, 565, 2254, 5034, 5381, 3238, 6512, 67, 6639, 2664, 5127, 59, 2203, 67, 16193, 273, 374, 5297, 71, 4763, 40, 1880, 38, 26, 9172, 22, 73, 39, 25, 7235, 9222, 5718, 70, 40, 10689, 1105, 73, 40, 28, 4700, 23, 69, 38, 71, 5608, 39, 24, 12648, 12648, 9449, 31, 203, 565, 2254, 5034, 5381, 3238, 453, 1258, 3587, 47, 3991, 59, 2203, 67, 4066, 7937, 67, 12919, 67, 5572, 67, 15920, 273, 374, 7669, 20, 72, 24, 71, 24, 4315, 20, 5193, 28, 71, 11180, 7358, 24, 8313, 21, 74, 7616, 28, 72, 27, 1611, 23, 1340, 26, 17156, 70, 2947, 8285, 23, 24852, 22, 3600, 11180, 2 ]
pragma solidity ^0.4.11; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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 SOFTWARE. */ pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal 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 returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal 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); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> contract Deadpool2RottenorFresh is usingOraclize { /* Declaration */ address public OWNERS = 0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A; uint public constant COMMISSION = 0; // Commission for the owner uint public constant MIN_BET = 0.01 ether; uint public EXPECTED_START = 1523818800; // When the bet's event is expected to start uint public EXPECTED_END = 1527274800; // When the bet's event is expected to end uint public constant BETTING_OPENS = 1522990923; uint public BETTING_CLOSES = EXPECTED_START - 60; // Betting closes a minute before the bet event starts uint public constant PING_ORACLE_INTERVAL = 60 * 60 * 24; // Ping oracle every 24 hours until completion (or cancelation) uint public ORACLIZE_GAS = 200000; uint public CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24; // Cancelation date is 24 hours after the expected end uint public RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30; // Any leftover money is returned to owners 1 month after bet ends bool public completed; bool public canceled; bool public ownersPayed; uint public ownerPayout; bool public returnedToOwners; uint public winnerDeterminedDate; uint public numCollected = 0; bytes32 public nextScheduledQuery; uint public oraclizeFees; uint public collectionFees; struct Better { uint betAmount; uint betOption; bool withdrawn; } mapping(address => Better) betterInfo; address[] public betters; uint[2] public totalAmountsBet; uint[2] public numberOfBets; uint public totalBetAmount; uint public winningOption = 2; /* Events */ event BetMade(); /* Modifiers */ // Modifier to only allow the // determination of the winner modifier canDetermineWinner() { require (winningOption == 2 && !completed && !canceled && now > BETTING_CLOSES && now >= EXPECTED_END); _; } // Modifier to only allow emptying // the remaining value of the contract // to owners. modifier canEmptyRemainings() { require(canceled || completed); uint numRequiredToCollect = canceled ? (numberOfBets[0] + numberOfBets[1]) : numberOfBets[winningOption]; require ((now >= RETURN_DATE && !canceled) || (numCollected == numRequiredToCollect)); _; } // Modifier to only allow the collection // of bet payouts when winner is determined, // (or withdrawals if the bet is canceled) modifier collectionsEnabled() { require (canceled || (winningOption != 2 && completed && now > BETTING_CLOSES)); _; } // Modifier to only allow the execution of // owner payout when winner is determined modifier canPayOwners() { require (!canceled && winningOption != 2 && completed && !ownersPayed && now > BETTING_CLOSES); _; } // Modifier to only allow the execution of // certain functions when betting is closed modifier bettingIsClosed() { require (now >= BETTING_CLOSES); _; } // Modifier to only allow the execution of // certain functions restricted to the owners modifier onlyOwnerLevel() { require( OWNERS == msg.sender ); _; } /* Functions */ // Constructor function Deadpool2RottenorFresh() public payable { oraclize_setCustomGasPrice(1000000000); callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for outcome } function changeGasLimitAndPrice(uint gas, uint price) public onlyOwnerLevel { ORACLIZE_GAS = gas; oraclize_setCustomGasPrice(price); } // Change bet expected times function setExpectedTimes(uint _EXPECTED_START, uint _EXPECTED_END) public onlyOwnerLevel { setExpectedStart(_EXPECTED_START); setExpectedEnd(_EXPECTED_END); } // Change bet expected start time function setExpectedStart(uint _EXPECTED_START) public onlyOwnerLevel { EXPECTED_START = _EXPECTED_START; BETTING_CLOSES = EXPECTED_START - 60; } // Change bet expected end time function setExpectedEnd(uint _EXPECTED_END) payable public onlyOwnerLevel { require(_EXPECTED_END > EXPECTED_START); EXPECTED_END = _EXPECTED_END; CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24; RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30; callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for winner } function callOracle(uint timeOrDelay, uint gas) private { require(canceled != true && completed != true); // Make a call to the oracle — // usually a script hosted on IPFS that // Oraclize deploys, after a given delay. We // leave nested query as default to maximize // optionality for queries. // To readers of the code (aka prospective betters) // if this is a computation query, you can view the // script we use to compute the winner, as it is hosted // on IPFS. The first argument in the computation query // is the IPFS hash (script would be located at // ipfs.io/ipfs/<HASH>). The file hosted at this hash // is actually a zipped folder that contains a Dockerfile and // the script. So, if you download the file at the hash provided, // ensure to convert it to a .zip, unzip it, and read the code. // Oraclize uses the Dockerfile to deploy this script. // Look over the Oraclize documentation to verify this // for yourself. nextScheduledQuery = makeOraclizeQuery(timeOrDelay, "nested", "[computation] ['QmVqSjNY64VfpnE3sZZZ7rv1uUpZRW9D8BXsbiNnwSGgmN', 'deadpool_2']", gas); } function makeOraclizeQuery(uint timeOrDelay, string datasource, string query, uint gas) private returns(bytes32) { oraclizeFees += oraclize_getPrice(datasource, gas); return oraclize_query(timeOrDelay, datasource, query, gas); } // Determine the outcome manually, // immediately function determineWinner(uint gas, uint gasPrice) payable public onlyOwnerLevel canDetermineWinner { ORACLIZE_GAS = gas; oraclize_setCustomGasPrice(gasPrice); callOracle(0, ORACLIZE_GAS); } // Callback from Oraclize function __callback(bytes32 queryId, string result, bytes proof) public canDetermineWinner { require(msg.sender == oraclize_cbAddress()); // The Oracle must always return // an integer (either 0 or 1, or if not then) // it should be 2 if (keccak256(result) != keccak256("0") && keccak256(result) != keccak256("1")) { // Reschedule winner determination, // unless we're past the point of // cancelation. If nextScheduledQuery is // not the current query, it means that // there's a scheduled future query, so // we can wait for that instead of scheduling // another one now (otherwise this would cause // dupe queries). if (now >= CANCELATION_DATE) { cancel(); } else if (nextScheduledQuery == queryId) { callOracle(PING_ORACLE_INTERVAL, ORACLIZE_GAS); } } else { setWinner(parseInt(result)); } } function setWinner(uint winner) private { completed = true; canceled = false; winningOption = winner; winnerDeterminedDate = now; payOwners(); } // Returns the total amounts betted // for the sender function getUserBet(address addr) public constant returns(uint[]) { uint[] memory bets = new uint[](2); bets[betterInfo[addr].betOption] = betterInfo[addr].betAmount; return bets; } // Returns whether a user has withdrawn // money or not. function userHasWithdrawn(address addr) public constant returns(bool) { return betterInfo[addr].withdrawn; } // Returns whether winning collections are // now available, or not. function collectionsAvailable() public constant returns(bool) { return (completed && winningOption != 2 && now >= (winnerDeterminedDate + 600)); // At least 10 mins has to pass between determining winner and enabling payout, so that we have time to revert the bet in case we detect suspicious betting activty (eg. a hacker bets a lot to steal the entire losing pot, and hacks the oracle) } // Returns true if we can bet (in betting window) function canBet() public constant returns(bool) { return (now >= BETTING_OPENS && now < BETTING_CLOSES && !canceled && !completed); } // Function for user to bet on launch // outcome function bet(uint option) public payable { require(canBet() == true); require(msg.value >= MIN_BET); require(betterInfo[msg.sender].betAmount == 0 || betterInfo[msg.sender].betOption == option); // Add better to better list if they // aren't already in it if (betterInfo[msg.sender].betAmount == 0) { betterInfo[msg.sender].betOption = option; numberOfBets[option]++; betters.push(msg.sender); } // Perform bet betterInfo[msg.sender].betAmount += msg.value; totalBetAmount += msg.value; totalAmountsBet[option] += msg.value; BetMade(); // Trigger event } // Empty remainder of the value in the // contract to the owners. function emptyRemainingsToOwners() private canEmptyRemainings { OWNERS.transfer(this.balance); returnedToOwners = true; } function returnToOwners() public onlyOwnerLevel canEmptyRemainings { emptyRemainingsToOwners(); } // Performs payout to owners function payOwners() private canPayOwners { if (COMMISSION == 0) { ownersPayed = true; ownerPayout = 0; collectionFees = ((oraclizeFees != 0) ? (oraclizeFees / numberOfBets[winningOption] + 1) : 0); // We add 1 wei to act as a ceil for the integer div -- important because the contract cannot afford to lose that spare change, as it will gaurantee that the final payout collection will fail. return; } // Calculate total pool of ETH // betted for the two outcomes. uint losingChunk = totalAmountsBet[1 - winningOption]; ownerPayout = (losingChunk - oraclizeFees) / COMMISSION; // Payout to the owner; commission of losing pot, minus the same % of the fees collectionFees = ((oraclizeFees != 0) ? ((oraclizeFees - oraclizeFees / COMMISSION) / numberOfBets[winningOption] + 1) : 0); // The fees to be distributed to the collectors, after owner payout. See reasoning above for adding the 1 wei. // Equal weight payout to the owners OWNERS.transfer(ownerPayout); ownersPayed = true; } function cancelBet() payable public onlyOwnerLevel { cancel(); } // Cancel bet and relase all the bets back to // the betters if, for any reason, payouts cannot be // completed. (For example Oracle fails.) Triggered by owners. function cancel() private { canceled = true; completed = false; } // Fallback function in case someone sends // ether to the contract so it doesn't get // lost. Could be used by us owners as buffer // value in case payouts fail. function() payable public { } // Function that lets betters collect their // money, either if the bet was canceled, // or if they won. function collect() public collectionsEnabled { address better = msg.sender; require(betterInfo[better].betAmount > 0); require(!betterInfo[better].withdrawn); require(canceled != completed); require(canceled || (completed && betterInfo[better].betOption == winningOption)); require(now >= (winnerDeterminedDate + 600)); uint payout = 0; if (!canceled) { // On top of their original bet, // add in profit, which is a weighted // proportion of the losing pot, relative // to their contribution to the winning pot, // minus owner commission. uint losingChunk = totalAmountsBet[1 - winningOption]; payout = betterInfo[better].betAmount + (betterInfo[better].betAmount * (losingChunk - ownerPayout) / totalAmountsBet[winningOption]) - collectionFees; } else { payout = betterInfo[better].betAmount; } if (payout > 0) { better.transfer(payout); betterInfo[better].withdrawn = true; numCollected++; } } }
Returns whether a user has withdrawn money or not.
function userHasWithdrawn(address addr) public constant returns(bool) { return betterInfo[addr].withdrawn; }
944
[ 1, 1356, 2856, 279, 729, 711, 598, 9446, 82, 15601, 578, 486, 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, 225, 445, 729, 5582, 1190, 9446, 82, 12, 2867, 3091, 13, 1071, 5381, 1135, 12, 6430, 13, 288, 203, 565, 327, 7844, 966, 63, 4793, 8009, 1918, 9446, 82, 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 ]
/* || THE LEXDAO REGISTRY (TLDR) || version 0.3 DEAR MSG.SENDER(S): / TLDR is a project in beta. // Please audit and use at your own risk. /// Entry into TLDR shall not create an attorney/client relationship. //// Likewise, TLDR should not be construed as legal advice or replacement for professional counsel. ///// STEAL THIS C0D3SL4W || lexDAO || ~presented by Open, ESQ LLC_DAO~ < https://mainnet.aragon.org/#/openesquire/ > */ pragma solidity 0.5.9; /*************** OPENZEPPELIN REFERENCE CONTRACTS - SafeMath, ScribeRole, ERC-20 transactional scripts ***************/ /** * @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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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]; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ScribeRole is Context { using Roles for Roles.Role; event ScribeAdded(address indexed account); event ScribeRemoved(address indexed account); Roles.Role private _Scribes; constructor () internal { _addScribe(_msgSender()); } modifier onlyScribe() { require(isScribe(_msgSender()), "ScribeRole: caller does not have the Scribe role"); _; } function isScribe(address account) public view returns (bool) { return _Scribes.has(account); } function renounceScribe() public { _removeScribe(_msgSender()); } function _addScribe(address account) internal { _Scribes.add(account); emit ScribeAdded(account); } function _removeScribe(address account) internal { _Scribes.remove(account); emit ScribeRemoved(account); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /*************** TLDR CONTRACT ***************/ contract TLDR is ScribeRole, ERC20 { // TLDR: Curated covenant & escrow scriptbase with incentivized arbitration using SafeMath for uint256; // lexDAO reference for lexScribe reputation governance fees (Ξ) address payable public lexDAO; // TLDR (LEX) ERC-20 token references address public tldrAddress = address(this); ERC20 tldrToken = ERC20(tldrAddress); string public name = "TLDR"; string public symbol = "LEX"; uint8 public decimals = 18; // counters for lexScribe lexScriptWrapper and registered DR (rdr) / DC (rdc) uint256 public LSW; // number of lexScriptWrapper enscribed uint256 public RDC; // number of rdc uint256 public RDR; // number of rdr // mapping for lexScribe reputation governance program mapping(address => uint256) public reputation; // mapping lexScribe reputation points mapping(address => uint256) public lastActionTimestamp; // mapping Unix timestamp of lexScribe governance actions (cooldown) mapping(address => uint256) public lastSuperActionTimestamp; // mapping Unix timestamp of material lexScribe governance actions requiring longer cooldown (icedown) // mapping for stored lexScript wrappers and registered digital retainers (DR / rdr) mapping (uint256 => lexScriptWrapper) public lexScript; // mapping registered lexScript 'wet code' templates mapping (uint256 => DC) public rdc; // mapping rdc call numbers for inspection and signature revocation mapping (uint256 => DR) public rdr; // mapping rdr call numbers for inspection and scripted payments struct lexScriptWrapper { // LSW: rdr lexScript templates maintained by lexScribes address lexScribe; // lexScribe (0x) address that enscribed lexScript template into TLDR / can make subsequent edits (lexVersion) address lexAddress; // (0x) address to receive lexScript wrapper lexFee / adjustable by associated lexScribe string templateTerms; // lexScript template terms to wrap rdr with legal security uint256 lexID; // number to reference in rdr to import lexScript terms uint256 lexVersion; // version number to mark lexScribe edits uint256 lexRate; // fixed divisible rate for lexFee in drToken per rdr payment made thereunder / e.g., 100 = 1% lexFee on rdr payDR transaction } struct DC { // Digital Covenant lexScript templates maintained by lexScribes address signatory; // DC signatory (0x) address string templateTerms; // DC templateTerms imported from referenced lexScriptWrapper string signatureDetails; // DC may include signatory name or other supplementary info uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security uint256 dcNumber; // DC number generated on signed covenant registration / identifies DC for signatory revocation uint256 timeStamp; // block.timestamp ("now") of DC registration bool revoked; // tracks signatory revocation status on DC } struct DR { // Digital Retainer created on lexScript terms maintained by lexScribes / data registered for escrow script address client; // rdr client (0x) address address provider; // provider (0x) address that receives ERC-20 payments in exchange for goods or services (deliverable) address drToken; // ERC-20 digital token (0x) address used to transfer value on Ethereum under rdr string deliverable; // description of deliverable retained for benefit of Ethereum payments uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security / default '1' for generalized rdr lexScript template uint256 drNumber; // rdr number generated on DR registration / identifies rdr for payDR function calls uint256 timeStamp; // block.timestamp ("now") of registration used to calculate retainerTermination UnixTime uint256 retainerTermination; // termination date of rdr in UnixTime / locks payments to provider / after, remainder can be withrawn by client uint256 deliverableRate; // rate for rdr deliverables in wei amount / 1 = 1000000000000000000 uint256 paid; // tracking amount of designated ERC-20 digital value paid under rdr in wei amount for payCap logic uint256 payCap; // value cap limit on rdr payments in wei amount bool confirmed; // tracks client countersignature status bool disputed; // tracks dispute status from client or provider / if called, locks remainder of escrow rdr payments for reputable lexScribe resolution } constructor(string memory tldrTerms, uint256 tldrLexRate, address tldrLexAddress, address payable _lexDAO) public { // deploys TLDR contract & stores base lexScript reputation[msg.sender] = 1; // sets TLDR summoner lexScribe reputation to '1' initial value lexDAO = _lexDAO; // sets initial lexDAO (0x) address LSW = LSW.add(1); // counts initial 'tldr' entry to LSW lexScript[1] = lexScriptWrapper( // populates default '1' lexScript data for reference in LSW and rdr msg.sender, tldrLexAddress, tldrTerms, 1, 0, tldrLexRate); } // TLDR Contract Events event Enscribed(uint256 indexed lexID, uint256 indexed lexVersion, address indexed lexScribe); // triggered on successful LSW creation / edits to LSW event Signed(uint256 indexed lexID, uint256 indexed dcNumber, address indexed signatory); // triggered on successful DC creation / edits to DC event Registered(uint256 indexed drNumber, uint256 indexed lexID, address indexed provider); // triggered on successful rdr event Confirmed(uint256 indexed drNumber, uint256 indexed lexID, address indexed client); // triggered on successful rdr confirmation event Paid(uint256 indexed drNumber, uint256 indexed lexID); // triggered on successful rdr payments event Disputed(uint256 indexed drNumber); // triggered on rdr dispute event Resolved(uint256 indexed drNumber); // triggered on successful rdr dispute resolution /*************** TLDR GOVERNANCE FUNCTIONS ***************/ // restricts lexScribe TLDR reputation governance function calls to once per day (cooldown) modifier cooldown() { require(now.sub(lastActionTimestamp[msg.sender]) > 1 days); // enforces cooldown period _; lastActionTimestamp[msg.sender] = now; // block.timestamp, "now" } // restricts material lexScribe TLDR reputation staking and lexDAO governance function calls to once per 90 days (icedown) modifier icedown() { require(now.sub(lastSuperActionTimestamp[msg.sender]) > 90 days); // enforces icedown period _; lastSuperActionTimestamp[msg.sender] = now; // block.timestamp, "now" } // lexDAO can add new lexScribe to maintain TLDR function addScribe(address account) public { require(msg.sender == lexDAO); _addScribe(account); reputation[account] = 1; } // lexDAO can remove lexScribe from TLDR / slash reputation function removeScribe(address account) public { require(msg.sender == lexDAO); _removeScribe(account); reputation[account] = 0; } // lexDAO can update (0x) address receiving reputation governance stakes (Ξ) / maintaining lexScribe registry function updateLexDAO(address payable newLexDAO) public { require(msg.sender == lexDAO); require(newLexDAO != address(0)); // program safety check / newLexDAO cannot be "0" burn address lexDAO = newLexDAO; // updates lexDAO (0x) address } // lexScribes can submit ether (Ξ) value for TLDR reputation and special TLDR function access (TLDR write privileges, rdr dispute resolution role) function submitETHreputation() payable public onlyScribe icedown { require(msg.value == 0.1 ether); // tenth of ether (Ξ) fee for refreshing reputation in lexDAO reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer address(lexDAO).transfer(msg.value); // transfers ether value (Ξ) to designated lexDAO (0x) address } // lexScribes can burn minted LEX value for TLDR reputation function submitLEXreputation() public onlyScribe icedown { _burn(_msgSender(), 10000000000000000000); // 10 LEX burned reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer } // public check on lexScribe reputation status function isReputable(address x) public view returns (bool) { // returns true if lexScribe is reputable return reputation[x] > 0; } // reputable lexScribes can reduce reputation within cooldown period function reduceScribeRep(address reducedLexScribe) cooldown public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable require(msg.sender != reducedLexScribe); // program governance check / cannot reduce own reputation reputation[reducedLexScribe] = reputation[reducedLexScribe].sub(1); // reduces reputation by "1" } // reputable lexScribes can repair reputation within cooldown period function repairScribeRep(address repairedLexScribe) cooldown public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable require(msg.sender != repairedLexScribe); // program governance check / cannot repair own reputation require(reputation[repairedLexScribe] < 3); // program governance check / cannot repair fully reputable lexScribe require(reputation[repairedLexScribe] > 0); // program governance check / cannot repair disreputable lexScribe reputation[repairedLexScribe] = reputation[repairedLexScribe].add(1); // repairs reputation by "1" } /*************** TLDR LEXSCRIBE FUNCTIONS ***************/ // reputable lexScribes can register lexScript legal wrappers on TLDR and program ERC-20 lexFees associated with lexID / LEX mint, "1" function writeLexScript(string memory templateTerms, uint256 lexRate, address lexAddress) public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable uint256 lexID = LSW.add(1); // reflects new lexScript value for tracking lexScript wrappers LSW = LSW.add(1); // counts new entry to LSW lexScript[lexID] = lexScriptWrapper( // populate lexScript data for rdr / rdc usage msg.sender, lexAddress, templateTerms, lexID, 0, lexRate); _mint(msg.sender, 1000000000000000000); // mints lexScribe "1" LEX for contribution to TLDR emit Enscribed(lexID, 0, msg.sender); } // lexScribes can update TLDR lexScript wrappers with new templateTerms and (0x) newLexAddress / version up LSW function editLexScript(uint256 lexID, string memory templateTerms, address lexAddress) public { lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data require(msg.sender == lS.lexScribe); // program safety check / authorization uint256 lexVersion = lS.lexVersion.add(1); // updates lexVersion lexScript[lexID] = lexScriptWrapper( // populates updated lexScript data for rdr / rdc usage msg.sender, lexAddress, templateTerms, lexID, lexVersion, lS.lexRate); emit Enscribed(lexID, lexVersion, msg.sender); } /*************** TLDR MARKET FUNCTIONS ***************/ // public can sign and associate (0x) identity with lexScript digital covenant wrapper function signDC(uint256 lexID, string memory signatureDetails) public { // sign Digital Covenant with (0x) address require(lexID > (0)); // program safety check require(lexID <= LSW); // program safety check lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data uint256 dcNumber = RDC.add(1); // reflects new rdc value for public inspection and signature revocation RDC = RDC.add(1); // counts new entry to RDC rdc[dcNumber] = DC( // populates rdc data msg.sender, lS.templateTerms, signatureDetails, lexID, dcNumber, now, false); emit Signed(lexID, dcNumber, msg.sender); } // registered DC signatories can revoke (0x) signature function revokeDC(uint256 dcNumber) public { // revoke Digital Covenant signature with (0x) address DC storage dc = rdc[dcNumber]; // retrieve rdc data require(msg.sender == dc.signatory); // program safety check / authorization rdc[dcNumber] = DC(// updates rdc data msg.sender, "Signature Revoked", // replaces Digital Covenant terms with revocation message dc.signatureDetails, dc.lexID, dc.dcNumber, now, // updates to revocation block.timestamp true); // reflects revocation status emit Signed(dc.lexID, dcNumber, msg.sender); } // goods and/or service providers can register DR with TLDR lexScript (lexID) function registerDR( // rdr address client, address drToken, string memory deliverable, uint256 retainerDuration, uint256 deliverableRate, uint256 payCap, uint256 lexID) public { require(lexID > (0)); // program safety check require(lexID <= LSW); // program safety check require(deliverableRate <= payCap); // program safety check / economics uint256 drNumber = RDR.add(1); // reflects new rdr value for inspection and escrow management uint256 retainerTermination = now.add(retainerDuration); // rdr termination date in UnixTime, "now" block.timestamp + retainerDuration RDR = RDR.add(1); // counts new entry to RDR rdr[drNumber] = DR( // populate rdr data client, msg.sender, drToken, deliverable, lexID, drNumber, now, // block.timestamp, "now" retainerTermination, deliverableRate, 0, payCap, false, false); emit Registered(drNumber, lexID, msg.sender); } // rdr client can confirm rdr offer script and countersign drNumber / trigger escrow deposit in approved payCap amount function confirmDR(uint256 drNumber) public { DR storage dr = rdr[drNumber]; // retrieve rdr data require(dr.confirmed == false); // program safety check / status require(now <= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client); // program safety check / authorization dr.confirmed = true; // reflect rdr client countersignature ERC20 drTokenERC20 = ERC20(dr.drToken); drTokenERC20.transferFrom(msg.sender, address(this), dr.payCap); // escrows payCap amount in approved drToken into TLDR emit Confirmed(drNumber, dr.lexID, msg.sender); } // rdr client can call to delegate role function delegateDRclient(uint256 drNumber, address clientDelegate) public { DR storage dr = rdr[drNumber]; // retrieve rdr data require(dr.disputed == false); // program safety check / status require(now <= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client); // program safety check / authorization require(dr.paid < dr.payCap); // program safety check / economics dr.client = clientDelegate; // updates rdr client address to delegate } // rdr parties can initiate dispute and lock escrowed remainder of rdr payCap in TLDR until resolution by reputable lexScribe function disputeDR(uint256 drNumber) public { DR storage dr = rdr[drNumber]; // retrieve rdr data require(dr.confirmed == true); // program safety check / status require(dr.disputed == false); // program safety check / status require(now <= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client || msg.sender == dr.provider); // program safety check / authorization require(dr.paid < dr.payCap); // program safety check / economics dr.disputed = true; // updates rdr value to reflect dispute status, "true" emit Disputed(drNumber); } // reputable lexScribe can resolve rdr dispute with division of remaining payCap amount in wei accounting for 5% fee / LEX mint, "1" function resolveDR(uint256 drNumber, uint256 clientAward, uint256 providerAward) public { DR storage dr = rdr[drNumber]; // retrieve rdr data uint256 remainder = dr.payCap.sub(dr.paid); // alias remainder rdr wei amount for rdr resolution reference uint256 resolutionFee = remainder.div(20); // calculates 5% lexScribe dispute resolution fee require(dr.disputed == true); // program safety check / status require(clientAward.add(providerAward) == remainder.sub(resolutionFee)); // program safety check / economics require(msg.sender != dr.client); // program safety check / authorization / client cannot resolve own dispute as lexScribe require(msg.sender != dr.provider); // program safety check / authorization / provider cannot resolve own dispute as lexScribe require(isReputable(msg.sender)); // program governance check / resolving lexScribe must be reputable require(balanceOf(msg.sender) >= 5000000000000000000); // program governance check / resolving lexScribe must have at least "5" LEX balance ERC20 drTokenERC20 = ERC20(dr.drToken); drTokenERC20.transfer(dr.client, clientAward); // executes ERC-20 award transfer to rdr client drTokenERC20.transfer(dr.provider, providerAward); // executes ERC-20 award transfer to rdr provider drTokenERC20.transfer(msg.sender, resolutionFee); // executes ERC-20 fee transfer to resolving lexScribe _mint(msg.sender, 1000000000000000000); // mints resolving lexScribe "1" LEX for contribution to TLDR dr.paid = dr.paid.add(remainder); // tallies remainder to paid wei amount to reflect rdr closure emit Resolved(drNumber); } // client can call to pay rdr on TLDR function payDR(uint256 drNumber) public { // releases escrowed drToken deliverableRate amount to provider (0x) address / lexFee for attached lexID lexAddress DR storage dr = rdr[drNumber]; // retrieve rdr data lexScriptWrapper storage lS = lexScript[dr.lexID]; // retrieve LSW data require(dr.confirmed == true); // program safety check / status require(dr.disputed == false); // program safety check / status require(now <= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client); // program safety check / authorization require(dr.paid.add(dr.deliverableRate) <= dr.payCap); // program safety check / economics uint256 lexFee = dr.deliverableRate.div(lS.lexRate); // derives lexFee from rdr deliverableRate ERC20 drTokenERC20 = ERC20(dr.drToken); drTokenERC20.transfer(dr.provider, dr.deliverableRate.sub(lexFee)); // executes ERC-20 transfer to rdr provider in deliverableRate amount drTokenERC20.transfer(lS.lexAddress, lexFee); // executes ERC-20 transfer of lexFee to (0x) lexAddress identified in lexID dr.paid = dr.paid.add(dr.deliverableRate); // tracks total ERC-20 wei amount paid under rdr / used to calculate rdr remainder emit Paid(drNumber, dr.lexID); } // client can call to withdraw rdr remainder on TLDR after termination function withdrawRemainder(uint256 drNumber) public { DR storage dr = rdr[drNumber]; // retrieve rdr data require(dr.confirmed == true); // program safety check / status require(dr.disputed == false); // program safety check / status require(now >= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client); // program safety check / authorization uint256 remainder = dr.payCap.sub(dr.paid); // derive rdr remainder ERC20 drTokenERC20 = ERC20(dr.drToken); require(remainder > 0); // program safety check / economics drTokenERC20.transfer(dr.client, remainder); // executes ERC-20 transfer to rdr client in escrow remainder amount dr.paid = dr.paid.add(remainder); // tallies remainder to paid wei amount to reflect rdr closure } }
sign Digital Covenant with (0x) address
function signDC(uint256 lexID, string memory signatureDetails) public {
983,211
[ 1, 2977, 11678, 7053, 385, 1527, 6602, 598, 261, 20, 92, 13, 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 ]
[ 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, 1573, 5528, 12, 11890, 5034, 5275, 734, 16, 533, 3778, 3372, 3790, 13, 1071, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x1e6D2aE4735d005D6929F5bc148A0881cF63d923/sources/project_/contracts/Orderbook.sol
Call getupdateFee on Pyth contract.
function pyth_update_fee( bytes[] calldata priceUpdateData ) public view returns (uint256 fee) { fee = pyth.getUpdateFee(priceUpdateData.length); }
9,456,456
[ 1, 1477, 336, 2725, 14667, 603, 4707, 451, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2395, 451, 67, 2725, 67, 21386, 12, 203, 3639, 1731, 8526, 745, 892, 6205, 1891, 751, 203, 565, 262, 1071, 1476, 1135, 261, 11890, 5034, 14036, 13, 288, 203, 3639, 14036, 273, 2395, 451, 18, 588, 1891, 14667, 12, 8694, 1891, 751, 18, 2469, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract GiveTheMoneyBack { address public owner; // creator of the contract address public receiver; // person who owes money address[] public backers; // people who back up the request uint256 public nbBackers; // Number of persons who backed the requests. uint256 public amount; // amount of wei owed string public description; // why the money is owed /* Generates a public event that notify clients when a new user backes the request */ event Backed(address backer); /* Generates a public event that notify clients when the receiver has given the money back */ event MoneyGivenBack(uint256 amountToDistribute); /** * Constructor * * @param receiverAddress address of the one who owes ether * @param etherAmount amount of ether owed * @param explanation explanation of the request */ function GiveTheMoneyBack(address receiverAddress, uint256 etherAmount, string explanation) public { owner = msg.sender; receiver = receiverAddress; amount = etherAmount * 10 ** 18; // converts the ether into wei. 1 ether = 10^18 wei description = explanation; backers.push(owner); // add the creator of the contract as a backer nbBackers = 1; } /** * Back up the request for money */ function backUp() public returns (bool) { /*require(msg.sender == receiver);*/ if (msg.sender == receiver) { return false; } for (uint i = 0; i < backers.length; i++) { /*require(backers[index] != msg.sender);*/ if (msg.sender == backers[i]) { return false; } } backers.push(msg.sender); nbBackers++; Backed(msg.sender); return true; } /** * Allows the receiver to pay his or her debts. */ function payDebt() public payable returns (bool) { if (msg.sender != receiver || msg.value != amount) { return false; } uint nbBackers = backers.length; uint256 amountToDistribute = amount / nbBackers; for (uint index = 0; index < nbBackers; index++) { backers[index].transfer(amountToDistribute); } MoneyGivenBack(amountToDistribute); return true; } }
* Back up the request for money/require(msg.sender == receiver);*/require(backers[index] != msg.sender);*/
function backUp() public returns (bool) { if (msg.sender == receiver) { return false; } for (uint i = 0; i < backers.length; i++) { if (msg.sender == backers[i]) { return false; } } backers.push(msg.sender); nbBackers++; Backed(msg.sender); return true; }
12,864,501
[ 1, 2711, 731, 326, 590, 364, 15601, 19, 6528, 12, 3576, 18, 15330, 422, 5971, 1769, 19, 6528, 12, 823, 414, 63, 1615, 65, 480, 1234, 18, 15330, 1769, 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, 1473, 1211, 1435, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 422, 5971, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1473, 414, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 3576, 18, 15330, 422, 1473, 414, 63, 77, 5717, 288, 203, 7734, 327, 629, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 1473, 414, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 4264, 2711, 414, 9904, 31, 203, 3639, 4297, 329, 12, 3576, 18, 15330, 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 ]
./partial_match/1/0xfd8b36E3A3206cfFAB7f1EF055643AF8d199725B/sources/ClearPoolStrategy.sol
* @title Represents an ownable resource./ The current owner of this resource.
contract CustomOwnable { address internal _owner; event OnOwnershipTransferred (address previousOwner, address newOwner); pragma solidity 0.8.10; modifier onlyOwner() { require(_owner == msg.sender, "Only owner"); _; } function transferOwnership (address addr) external virtual onlyOwner { require(addr != address(0), "non-zero address required"); emit OnOwnershipTransferred(_owner, addr); _owner = addr; } function owner () external virtual view returns (address) { return _owner; } }
15,552,512
[ 1, 23869, 87, 392, 4953, 429, 1058, 18, 19, 1021, 783, 3410, 434, 333, 1058, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6082, 5460, 429, 288, 203, 565, 1758, 2713, 389, 8443, 31, 203, 203, 565, 871, 2755, 5460, 12565, 1429, 4193, 261, 2867, 2416, 5541, 16, 1758, 394, 5541, 1769, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 2163, 31, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 24899, 8443, 422, 1234, 18, 15330, 16, 315, 3386, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 261, 2867, 3091, 13, 3903, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 4793, 480, 1758, 12, 20, 3631, 315, 5836, 17, 7124, 1758, 1931, 8863, 203, 3639, 3626, 2755, 5460, 12565, 1429, 4193, 24899, 8443, 16, 3091, 1769, 203, 3639, 389, 8443, 273, 3091, 31, 203, 565, 289, 203, 203, 565, 445, 3410, 1832, 3903, 5024, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 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 ]